1 ;;;; file system interface functions -- fairly Unix-centric, but with
2 ;;;; differences between Unix and Win32 papered over.
4 ;;;; This software is part of the SBCL system. See the README file for
7 ;;;; This software is derived from the CMU CL system, which was
8 ;;;; written at Carnegie Mellon University and released into the
9 ;;;; public domain. The software is in the public domain and is
10 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
11 ;;;; files for more information.
13 (in-package "SB!IMPL")
15 ;;;; Unix pathname host support
17 ;;; FIXME: the below shouldn't really be here, but in documentation
18 ;;; (chapter 19 makes a lot of requirements for documenting
19 ;;; implementation-dependent decisions), but anyway it's probably not
20 ;;; what we currently do.
22 ;;; Unix namestrings have the following format:
24 ;;; namestring := [ directory ] [ file [ type [ version ]]]
25 ;;; directory := [ "/" ] { file "/" }*
27 ;;; type := "." [^/.]*
28 ;;; version := "." ([0-9]+ | "*")
30 ;;; Note: this grammar is ambiguous. The string foo.bar.5 can be
31 ;;; parsed as either just the file specified or as specifying the
32 ;;; file, type, and version. Therefore, we use the following rules
33 ;;; when confronted with an ambiguous file.type.version string:
35 ;;; - If the first character is a dot, it's part of the file. It is not
36 ;;; considered a dot in the following rules.
38 ;;; - Otherwise, the last dot separates the file and the type.
40 ;;; Wildcard characters:
42 ;;; If the directory, file, type components contain any of the
43 ;;; following characters, it is considered part of a wildcard pattern
44 ;;; and has the following meaning.
46 ;;; ? - matches any one character
47 ;;; * - matches any zero or more characters.
48 ;;; [abc] - matches any of a, b, or c.
49 ;;; {str1,str2,...,strn} - matches any of str1, str2, ..., or strn.
50 ;;; (FIXME: no it doesn't)
52 ;;; Any of these special characters can be preceded by an escape
53 ;;; character to cause it to be treated as a regular character.
54 (defun remove-escape-characters (namestr start end escape-char
)
55 "Remove any occurrences of escape characters from the string
56 because we've already checked for whatever they may have
58 (declare (type simple-string namestr
)
59 (type index start end
))
60 (let* ((result (make-string (- end start
) :element-type
'character
))
63 (do ((src start
(1+ src
)))
66 (setf (schar result dst
) (schar namestr src
))
70 (let ((char (schar namestr src
)))
71 (cond ((char= char escape-char
)
74 (setf (schar result dst
) char
)
77 (error 'namestring-parse-error
78 :complaint
"escape char in a bad place"
81 (%shrink-vector result dst
)))
83 (defun maybe-make-pattern (namestr start end escape-char
)
84 (declare (type simple-string namestr
)
85 (type index start end
)
86 (type character escape-char
))
90 (last-regular-char nil
)
92 (flet ((flush-pending-regulars ()
93 (when last-regular-char
94 (pattern (if any-quotes
95 (remove-escape-characters
96 namestr last-regular-char
98 (subseq namestr last-regular-char index
)))
100 (setf last-regular-char nil
))))
104 (let ((char (schar namestr index
)))
108 ((char= char escape-char
)
111 (unless last-regular-char
112 (setf last-regular-char index
))
115 (flush-pending-regulars)
116 (pattern :single-char-wild
)
119 (flush-pending-regulars)
120 (pattern :multi-char-wild
)
123 (flush-pending-regulars)
125 (position #\
] namestr
:start index
:end end
)))
126 (unless close-bracket
127 (error 'namestring-parse-error
128 :complaint
"#\\[ with no corresponding #\\]"
131 (pattern (cons :character-set
135 (setf index
(1+ close-bracket
))))
137 (unless last-regular-char
138 (setf last-regular-char index
))
140 (flush-pending-regulars)))
141 (cond ((null (pattern))
143 ((null (cdr (pattern)))
144 (let ((piece (first (pattern))))
146 ((member :multi-char-wild
) :wild
)
147 (simple-string piece
)
149 (make-pattern (pattern))))))
151 (make-pattern (pattern))))))
153 (defun unparse-physical-piece (thing escape-char
)
157 (let* ((srclen (length thing
))
160 (let ((char (schar thing i
)))
164 (t (when (char= char escape-char
)
166 (let ((result (make-string dstlen
))
168 (dotimes (src srclen
)
169 (let ((char (schar thing src
)))
172 (setf (schar result dst
) escape-char
)
174 (t (when (char= char escape-char
)
175 (setf (schar result dst
) escape-char
)
177 (setf (schar result dst
) char
)
181 (with-simple-output-to-string (s)
182 (dolist (piece (pattern-pieces thing
))
185 (write-string piece s
))
189 (write-string "*" s
))
191 (write-string "?" s
))))
196 (write-string (cdr piece
) s
)
197 (write-string "]" s
))
199 (error "invalid pattern piece: ~S" piece
))))))))))
201 (defun make-matcher (piece)
202 (cond ((eq piece
:wild
)
204 ((typep piece
'pattern
)
206 (when (stringp other
)
207 (pattern-matches piece other
))))
210 (equal piece other
)))))
212 (/show0
"filesys.lisp 160")
214 (defun extract-name-type-and-version (namestr start end escape-char
)
215 (declare (type simple-string namestr
)
216 (type index start end
))
217 (let* ((last-dot (position #\. namestr
:start
(1+ start
) :end end
221 (values (maybe-make-pattern namestr start last-dot escape-char
)
222 (maybe-make-pattern namestr
(1+ last-dot
) end escape-char
)
225 (values (maybe-make-pattern namestr start end escape-char
)
229 (/show0
"filesys.lisp 200")
232 ;;;; Grabbing the kind of file when we have a namestring.
233 (defun native-file-kind (namestring)
234 (multiple-value-bind (existsp errno ino mode
)
236 (sb!unix
:unix-lstat namestring
)
238 (sb!unix
:unix-stat namestring
)
239 (declare (ignore errno ino
))
241 (let ((ifmt (logand mode sb
!unix
:s-ifmt
)))
243 (#.sb
!unix
:s-ifreg
:file
)
244 (#.sb
!unix
:s-ifdir
:directory
)
246 (#.sb
!unix
:s-iflnk
:symlink
)
249 ;;;; TRUENAME, PROBE-FILE, FILE-AUTHOR, FILE-WRITE-DATE.
251 ;;; Rewritten in 12/2007 by RMK, replacing 13+ year old CMU code that
252 ;;; made a mess of things in order to support search lists (which SBCL
253 ;;; has never had). These are now all relatively straightforward
254 ;;; wrappers around stat(2) and realpath(2), with the same basic logic
255 ;;; in all cases. The wrinkles to be aware of:
257 ;;; * SBCL defines the truename of an existing, dangling or
258 ;;; self-referring symlink to be the symlink itself.
259 ;;; * The old version of PROBE-FILE merged the pathspec against
260 ;;; *DEFAULT-PATHNAME-DEFAULTS* twice, and so lost when *D-P-D*
261 ;;; was a relative pathname. Even if the case where *D-P-D* is a
262 ;;; relative pathname is problematic, there's no particular reason
263 ;;; to get that wrong, so let's try not to.
264 ;;; * Note that while stat(2) is probably atomic, getting the truename
265 ;;; for a filename involves poking all over the place, and so is
266 ;;; subject to race conditions if other programs mutate the file
267 ;;; system while we're resolving symlinks. So it's not implausible for
268 ;;; realpath(3) to fail even if stat(2) succeeded. There's nothing
269 ;;; obvious we can do about this, however.
270 ;;; * Windows' apparent analogue of realpath(3) is called
271 ;;; GetFullPathName, and it's a bit less useful than realpath(3).
272 ;;; In particular, while realpath(3) errors in case the file doesn't
273 ;;; exist, GetFullPathName seems to return a filename in all cases.
274 ;;; As realpath(3) is not atomic anyway, we only ever call it when
275 ;;; we think a file exists, so just be careful when rewriting this
278 ;;; Given a pathname designator, some quality to query for, return one
279 ;;; of a pathname, a universal time, or a string (a file-author), or
280 ;;; NIL. QUERY-FOR may be one of :TRUENAME, :EXISTENCE, :WRITE-DATE,
281 ;;; :AUTHOR. If ERRORP is false, return NIL in case the file system
282 ;;; returns an error code; otherwise, signal an error. Accepts
283 ;;; logical pathnames, too (but never returns LPNs). For internal
285 (defun query-file-system (pathspec query-for
&optional
(errorp t
))
286 (let ((pathname (translate-logical-pathname
289 (sane-default-pathname-defaults)))))
290 (when (wild-pathname-p pathname
)
291 (error 'simple-file-error
293 :format-control
"~@<can't find the ~A of wild pathname ~A~
294 (physicalized from ~A).~:>"
295 :format-arguments
(list query-for pathname pathspec
)))
296 (macrolet ((fail (note-format pathname errno
)
297 ;; Do this as a macro to avoid evaluating format
298 ;; calls when ERROP is NIL
300 (simple-file-perror ,note-format
,pathname
,errno
)
301 (return-from query-file-system nil
))))
302 (let ((filename (native-namestring pathname
:as-file t
)))
305 ((:existence
:truename
)
306 (multiple-value-bind (file kind
)
307 (sb!win32
::native-probe-file-name filename
)
308 (when (and (not file
) kind
)
309 (setf file filename
))
310 ;; The following OR was an AND, but that breaks files like NUL,
311 ;; for which GetLongPathName succeeds yet GetFileAttributesEx
312 ;; fails to return the file kind. --DFL
315 (parse-native-namestring
317 (pathname-host pathname
)
318 (sane-default-pathname-defaults)
319 :as-directory
(eq :directory kind
)))
320 (fail (format nil
"Failed to find the ~A of ~~A" query-for
) filename
321 (sb!win32
:get-last-error
)))))
323 (or (sb!win32
::native-file-write-date filename
)
324 (fail (format nil
"Failed to find the ~A of ~~A" query-for
) filename
325 (sb!win32
:get-last-error
)))))
327 (multiple-value-bind (existsp errno ino mode nlink uid gid rdev size
329 (sb!unix
:unix-stat filename
)
330 (declare (ignore ino nlink gid rdev size atime
))
331 (labels ((parse (filename &key
(as-directory
336 (parse-native-namestring
338 (pathname-host pathname
)
339 (sane-default-pathname-defaults)
340 :as-directory as-directory
)))
341 (resolve-problematic-symlink (&optional realpath-failed
)
342 ;; SBCL has for many years had a policy that a pathname
343 ;; that names an existing, dangling or self-referential
344 ;; symlink denotes the symlink itself. stat(2) fails
345 ;; and sets errno to ENOENT or ELOOP respectively, but
346 ;; we must distinguish cases where the symlink exists
347 ;; from ones where there's a loop in the apparent
348 ;; containing directory.
349 ;; Also handles symlinks in /proc/pid/fd/ to
350 ;; pipes or sockets on Linux
351 (multiple-value-bind (linkp ignore ino mode nlink uid gid rdev
353 (sb!unix
:unix-lstat filename
)
354 (declare (ignore ignore ino mode nlink gid rdev size atime
))
355 (when (and (or (= errno sb
!unix
:enoent
)
356 (= errno sb
!unix
:eloop
)
359 (return-from query-file-system
362 ;; We do this reparse so as to return a
363 ;; normalized pathname.
364 (parse filename
:as-directory nil
))
366 ;; So here's a trick: since lstat succeded,
367 ;; FILENAME exists, so its directory exists and
368 ;; only the non-directory part is loopy. So
369 ;; let's resolve FILENAME's directory part with
370 ;; realpath(3), in order to get a canonical
371 ;; absolute name for the directory, and then
372 ;; return a pathname having PATHNAME's name,
373 ;; type, and version, but the rest from the
374 ;; truename of the directory. Since we turned
375 ;; PATHNAME into FILENAME "as a file", FILENAME
376 ;; does not end in a slash, and so we get the
377 ;; directory part of FILENAME by reparsing
378 ;; FILENAME and masking off its name, type, and
379 ;; version bits. But note not to call ourselves
380 ;; recursively, because we don't want to
381 ;; re-merge against *DEFAULT-PATHNAME-DEFAULTS*,
382 ;; since PATHNAME may be a relative pathname.
385 (multiple-value-bind (realpath errno
)
386 (sb!unix
:unix-realpath
392 :defaults
(parse filename
393 :as-directory nil
))))
395 (fail "couldn't resolve ~A" filename errno
)))
397 (if (directory-pathname-p pathname
)
398 (parse (car (last (pathname-directory pathname
)))
401 (:author
(sb!unix
:uid-username uid
))
402 (:write-date
(+ unix-to-universal-time mtime
))))))
403 ;; If we're still here, the file doesn't exist; error.
405 (format nil
"Failed to find the ~A of ~~A" query-for
)
409 (:existence
(parse filename
))
411 ;; Note: in case the file is stat'able, POSIX
412 ;; realpath(3) gets us a canonical absolute
413 ;; filename, even if the post-merge PATHNAME
415 (parse (or (sb!unix
:unix-realpath filename
)
416 (resolve-problematic-symlink t
))))
417 (:author
(sb!unix
:uid-username uid
))
418 (:write-date
(+ unix-to-universal-time mtime
)))
419 (resolve-problematic-symlink))))))))
422 (defun probe-file (pathspec)
423 "Return the truename of PATHSPEC if the truename can be found,
424 or NIL otherwise. See TRUENAME for more information."
425 (query-file-system pathspec
:truename nil
))
427 (defun truename (pathspec)
428 "If PATHSPEC is a pathname that names an existing file, return
429 a pathname that denotes a canonicalized name for the file. If
430 pathspec is a stream associated with a file, return a pathname
431 that denotes a canonicalized name for the file associated with
434 An error of type FILE-ERROR is signalled if no such file exists
435 or if the file system is such that a canonicalized file name
436 cannot be determined or if the pathname is wild.
438 Under Unix, the TRUENAME of a symlink that links to itself or to
439 a file that doesn't exist is considered to be the name of the
440 broken symlink itself."
441 ;; Note that eventually this routine might be different for streams
442 ;; than for other pathname designators.
443 (if (streamp pathspec
)
444 (query-file-system pathspec
:truename
)
445 (query-file-system pathspec
:truename
)))
447 (defun file-author (pathspec)
448 "Return the author of the file specified by PATHSPEC. Signal an
449 error of type FILE-ERROR if no such file exists, or if PATHSPEC
451 (query-file-system pathspec
:author
))
453 (defun file-write-date (pathspec)
454 "Return the write date of the file specified by PATHSPEC.
455 An error of type FILE-ERROR is signaled if no such file exists,
456 or if PATHSPEC is a wild pathname."
457 (query-file-system pathspec
:write-date
))
459 ;;;; miscellaneous other operations
461 (/show0
"filesys.lisp 700")
463 (defun rename-file (file new-name
)
464 "Rename FILE to have the specified NEW-NAME. If FILE is a stream open to a
465 file, then the associated file is renamed."
466 (let* ((original (merge-pathnames file
(sane-default-pathname-defaults)))
467 (old-truename (truename original
))
468 (original-namestring (native-namestring (physicalize-pathname original
)
470 (new-name (merge-pathnames new-name original
))
471 (new-namestring (native-namestring (physicalize-pathname new-name
)
473 (unless new-namestring
474 (error 'simple-file-error
476 :format-control
"~S can't be created."
477 :format-arguments
(list new-name
)))
478 (multiple-value-bind (res error
)
479 (sb!unix
:unix-rename original-namestring new-namestring
)
481 (error 'simple-file-error
483 :format-control
"~@<couldn't rename ~2I~_~A ~I~_to ~2I~_~A: ~
485 :format-arguments
(list original new-name
(strerror error
))))
487 (file-name file new-name
))
488 (values new-name old-truename
(truename new-name
)))))
490 (defun delete-file (file)
491 "Delete the specified FILE.
493 If FILE is a stream, on Windows the stream is closed immediately. On Unix
494 platforms the stream remains open, allowing IO to continue: the OS resources
495 associated with the deleted file remain available till the stream is closed as
496 per standard Unix unlink() behaviour."
497 (let* ((pathname (translate-logical-pathname
498 (merge-pathnames file
(sane-default-pathname-defaults))))
499 (namestring (native-namestring pathname
:as-file t
)))
503 (multiple-value-bind (res err
)
504 #!-win32
(sb!unix
:unix-unlink namestring
)
505 #!+win32
(or (sb!win32
::native-delete-file namestring
)
506 (values nil
(sb!win32
:get-last-error
)))
508 (simple-file-perror "couldn't delete ~A" namestring err
))))
511 (defun directorize-pathname (pathname)
512 (if (or (pathname-name pathname
)
513 (pathname-type pathname
))
514 (make-pathname :directory
(append (pathname-directory pathname
)
515 (list (file-namestring pathname
)))
516 :host
(pathname-host pathname
)
517 :device
(pathname-device pathname
))
520 (defun delete-directory (pathspec &key recursive
)
521 "Deletes the directory designated by PATHSPEC (a pathname designator).
522 Returns the truename of the directory deleted.
524 If RECURSIVE is false \(the default), signals an error unless the directory is
525 empty. If RECURSIVE is true, first deletes all files and subdirectories. If
526 RECURSIVE is true and the directory contains symbolic links, the links are
527 deleted, not the files and directories they point to.
529 Signals an error if PATHSPEC designates a file or a symbolic link instead of a
530 directory, or if the directory could not be deleted for any reason.
534 \(DELETE-DIRECTORY \"/tmp/foo\")
535 \(DELETE-DIRECTORY \"/tmp/foo/\")
537 delete the \"foo\" subdirectory of \"/tmp\", or signal an error if it does not
538 exist or if is a file or a symbolic link."
539 (declare (type pathname-designator pathspec
))
540 (let ((physical (directorize-pathname
541 (physicalize-pathname
543 pathspec
(sane-default-pathname-defaults))))))
544 (labels ((recurse-merged (dir)
546 (recurse (merge-pathnames sub dir
))))
549 (delete-file (merge-pathnames file dir
))))
551 (map-directory (recurse-merged dir
) dir
554 :classify-symlinks nil
)
555 (map-directory (delete-merged dir
) dir
558 :classify-symlinks nil
)
561 (let ((namestring (native-namestring dir
:as-file t
)))
562 (multiple-value-bind (res errno
)
564 (or (sb!win32
::native-delete-directory namestring
)
565 (values nil
(sb!win32
:get-last-error
)))
568 (not (minusp (alien-funcall
569 (extern-alien "rmdir"
570 (function int c-string
))
576 "Could not delete directory ~A"
577 namestring errno
))))))
580 (delete-dir physical
)))))
583 (sb!alien
:define-alien-variable
("sbcl_home" *sbcl-home
*) c-string
)
585 (defun sbcl-homedir-pathname ()
586 (let ((env (posix-getenv "SBCL_HOME")))
587 (parse-native-namestring (if (and env
(not (string= env
"")))
591 *default-pathname-defaults
*
594 (defun user-homedir-namestring (&optional username
)
595 (flet ((not-empty (x)
596 (and (not (equal x
"")) x
)))
598 (sb!unix
:user-homedir username
)
599 (or (not-empty (posix-getenv "HOME"))
601 (not-empty (posix-getenv "USERPROFILE"))
603 (let ((drive (not-empty (posix-getenv "HOMEDRIVE")))
604 (path (not-empty (posix-getenv "HOMEPATH"))))
606 (concatenate 'string drive path
)))
608 (not-empty (sb!unix
:uid-homedir
(sb!unix
:unix-getuid
)))
609 (error "Couldn't find home directory.")))))
611 ;;; (This is an ANSI Common Lisp function.)
612 (defun user-homedir-pathname (&optional host
)
613 "Return the home directory of the user as a pathname. If the HOME
614 environment variable has been specified, the directory it designates
615 is returned; otherwise obtains the home directory from the operating
616 system. HOST argument is ignored by SBCL."
617 (declare (ignore host
))
619 (parse-native-namestring
620 (or (user-homedir-namestring)
622 (sb!win32
::get-folder-namestring sb
!win32
::csidl_profile
))
624 *default-pathname-defaults
*
630 (defun directory (pathspec &key
(resolve-symlinks t
))
631 "Return a list of PATHNAMEs, each the TRUENAME of a file that matched the
632 given pathname. Note that the interaction between this ANSI-specified
633 TRUENAMEing and the semantics of the Unix filesystem (symbolic links..) means
634 this function can sometimes return files which don't have the same directory
635 as PATHNAME. If :RESOLVE-SYMLINKS is NIL, don't resolve symbolic links in
637 (let (;; We create one entry in this hash table for each truename,
638 ;; as an asymptotically efficient way of removing duplicates
639 ;; (which can arise when e.g. multiple symlinks map to the
641 (truenames (make-hash-table :test
#'equal
)))
642 (labels ((record (pathname)
643 (let ((truename (if resolve-symlinks
644 ;; FIXME: Why not not TRUENAME? As reported by
645 ;; Milan Zamazal sbcl-devel 2003-10-05, using
646 ;; TRUENAME causes a race condition whereby
647 ;; removal of a file during the directory
648 ;; operation causes an error. It's not clear
649 ;; what the right thing to do is, though. --
651 (query-file-system pathname
:truename nil
)
652 (query-file-system pathname
:existence nil
))))
654 (setf (gethash (namestring truename
) truenames
)
656 (do-physical-pathnames (pathname)
657 (aver (not (logical-pathname-p pathname
)))
658 (let* (;; KLUDGE: Since we don't canonize pathnames on construction,
659 ;; we really have to do it here to get #p"foo/." mean the same
661 (pathname (canonicalize-pathname pathname
))
662 (name (pathname-name pathname
))
663 (type (pathname-type pathname
))
664 (match-name (make-matcher name
))
665 (match-type (make-matcher type
)))
666 (map-matching-directories
669 (map-matching-entries #'record
675 (do-pathnames (pathname)
676 (if (logical-pathname-p pathname
)
677 (let ((host (intern-logical-host (pathname-host pathname
))))
678 (dolist (x (logical-host-canon-transls host
))
679 (destructuring-bind (from to
) x
681 (pathname-intersections pathname from
)))
682 (dolist (p intersections
)
683 (do-pathnames (translate-pathname p from to
)))))))
684 (do-physical-pathnames pathname
))))
685 (declare (truly-dynamic-extent #'record
))
686 (do-pathnames (merge-pathnames pathspec
)))
688 ;; Sorting isn't required by the ANSI spec, but sorting into some
689 ;; canonical order seems good just on the grounds that the
690 ;; implementation should have repeatable behavior when possible.
691 (sort (loop for namestring being each hash-key in truenames
692 using
(hash-value truename
)
693 collect
(cons namestring truename
))
697 (defun canonicalize-pathname (pathname)
698 ;; We're really only interested in :UNSPECIFIC -> NIL, :BACK and :UP,
699 ;; and dealing with #p"foo/.." and #p"foo/."
700 (labels ((simplify (piece)
701 (unless (eq :unspecific piece
)
703 (canonicalize-directory (directory)
705 (dolist (piece directory
)
707 ((and pieces
(member piece
'(:back
:up
)))
708 ;; FIXME: We should really canonicalize when we construct
709 ;; pathnames. This is just wrong.
711 ((:absolute
:wild-inferiors
)
712 (error 'simple-file-error
713 :format-control
"Invalid use of ~S after ~S."
714 :format-arguments
(list piece
(car pieces
))
716 ((:relative
:up
:back
)
721 ;; This case only really matters on Windows,
722 ;; because on POSIX, our call site (TRUENAME via
723 ;; QUERY-FILE-SYSTEM) only passes in pathnames from
724 ;; realpath(3), in which /./ has been removed
725 ;; already. Windows, however, depends on us to
726 ;; perform this fixup. -- DFL
729 (push piece pieces
))))
731 (let ((name (simplify (pathname-name pathname
)))
732 (type (simplify (pathname-type pathname
)))
733 (dir (canonicalize-directory (pathname-directory pathname
))))
735 ((not (equal "." name
))
736 (make-pathname :name name
:type type
:directory dir
739 (make-pathname :name nil
:defaults pathname
))
741 (make-pathname :name nil
:type nil
:directory
(butlast dir
)
744 (make-pathname :name name
:type type
:directory dir
745 :defaults pathname
))))))
747 ;;; Given a native namestring, provides a WITH-HASH-TABLE-ITERATOR style
748 ;;; interface to mapping over namestrings of entries in the corresponding
750 (defmacro with-native-directory-iterator
((iterator namestring
&key errorp
) &body body
)
751 (with-unique-names (one-iter)
753 ((iterate (,one-iter
)
754 (declare (type function
,one-iter
))
755 (macrolet ((,iterator
()
756 `(funcall ,',one-iter
)))
759 (sb!win32
::native-call-with-directory-iterator
760 #'iterate
,namestring
,errorp
)
762 (call-with-native-directory-iterator #'iterate
,namestring
,errorp
))))
764 (defun call-with-native-directory-iterator (function namestring errorp
)
765 (declare (type (or null string
) namestring
)
773 (let ((ent (sb!unix
:unix-readdir dp nil
)))
775 (let ((name (sb!unix
:unix-dirent-name ent
)))
777 (cond ((equal "." name
)
782 (return-from one-iter name
))))))))))
785 (setf dp
(sb!unix
:unix-opendir namestring errorp
))
787 (funcall function
#'one-iter
)))
789 (sb!unix
:unix-closedir dp nil
)))))))
791 ;;; This is our core directory access interface that we use to implement
793 (defun map-directory (function directory
&key
(files t
) (directories t
)
794 (classify-symlinks t
) (errorp t
))
795 "Map over entries in DIRECTORY. Keyword arguments specify which entries to
799 If true, call FUNCTION with the pathname of each file in DIRECTORY.
803 If true, call FUNCTION with a pathname for each subdirectory of DIRECTORY.
804 If :AS-FILES, the pathname used is a pathname designating the subdirectory
805 as a file in DIRECTORY. Otherwise the pathname used is a directory
806 pathname. Defaults to T.
809 If true, the decision to call FUNCTION with the pathname of a symbolic link
810 depends on the resolution of the link: if it points to a directory, it is
811 considered a directory entry, otherwise a file entry. If false, all
812 symbolic links are considered file entries. In both cases the pathname used
813 for the symbolic link is not fully resolved, but names it as an immediate
814 child of DIRECTORY. Defaults to T.
817 If true, signal an error if DIRECTORY does not exist, cannot be read, etc.
820 Experimental: interface subject to change."
821 (declare (pathname-designator directory
))
822 (let* ((fun (%coerce-callable-to-fun function
))
823 (as-files (eq :as-files directories
))
824 (physical (physicalize-pathname directory
))
825 (realname (query-file-system physical
:existence nil
))
826 (canonical (if realname
827 (parse-native-namestring realname
828 (pathname-host physical
)
829 (sane-default-pathname-defaults)
831 (return-from map-directory nil
)))
832 (dirname (native-namestring canonical
)))
833 (flet ((map-it (name dirp
)
835 (merge-pathnames (parse-native-namestring
837 :as-directory
(and dirp
(not as-files
)))
839 (with-native-directory-iterator (next dirname
:errorp errorp
)
841 ;; provision for FindFirstFileExW-based iterator that should be used
842 ;; on Windows: file kind is known instantly there, so we'll have it
843 ;; returned by (next) soon.
844 (multiple-value-bind (name kind
) (next)
845 (unless (or name kind
) (return))
847 (setf kind
(native-file-kind
848 (concatenate 'string dirname name
))))
855 (if classify-symlinks
856 (let* ((tmpname (merge-pathnames
857 (parse-native-namestring
858 name nil physical
:as-directory nil
)
860 (truename (query-file-system tmpname
:truename nil
)))
861 (if (or (not truename
)
862 (or (pathname-name truename
) (pathname-type truename
)))
864 (funcall fun tmpname
))
870 ;; Anything else parses as a file.
872 (map-it name nil
)))))))))))
874 ;;; Part of DIRECTORY: implements matching the directory spec. Calls FUNCTION
875 ;;; with all DIRECTORIES that match the directory portion of PATHSPEC.
876 (defun map-matching-directories (function pathspec
)
877 (binding* ((directory (pathname-directory pathspec
))
878 ((mode end
) (loop for component in directory
879 for i
:of-type index from
0
880 do
(typecase component
881 ((or (eql :wild
) pattern
)
882 (return (values :wild i
)))
883 ((eql :wild-inferiors
)
884 (return (values :wild-inferiors i
))))))
885 ((directory-start directory-rest
)
887 (values (subseq directory
0 end
) (subseq directory end
))
888 (values directory directory
)))
889 (starting-point (make-pathname :directory directory-start
890 :device
(pathname-device pathspec
)
891 :host
(pathname-host pathspec
)
895 (starting-point (or (probe-file starting-point
)
899 (map-wild-inferiors function directory-rest starting-point
))
901 (map-wild function directory-rest starting-point
))
902 (t ; Nothing wild -- the directory matches itself.
903 (funcall function starting-point
))))
906 (defun last-directory-piece (pathname)
907 (car (last (pathname-directory pathname
))))
909 ;;; Part of DIRECTORY: implements iterating over a :WILD or pattern component
910 ;;; in the directory spec.
911 (defun map-wild (function more directory
)
912 (let ((this (pop more
))
914 (flet ((cont (subdirectory)
917 (funcall function subdirectory
))
918 ((or (eq :wild next
) (typep next
'pattern
))
919 (map-wild function more subdirectory
))
920 ((eq :wild-inferiors next
)
921 (map-wild-inferiors function more subdirectory
))
923 (let ((this (pathname-directory subdirectory
)))
924 (map-matching-directories
926 (make-pathname :directory
(append this more
)
927 :defaults subdirectory
)))))))
932 (when (pattern-matches this
(last-directory-piece sub
))
933 (funcall #'cont sub
))))
939 ;;; Part of DIRECTORY: implements iterating over a :WILD-INFERIORS component
940 ;;; in the directory spec.
941 (defun map-wild-inferiors (function more directory
)
942 (loop while
(member (car more
) '(:wild
:wild-inferiors
))
944 (let ((next (car more
))
947 (funcall function directory
))
951 (funcall function pathname
)
952 (map-wild-inferiors function more pathname
)))
955 (let ((this (pathname-directory pathname
)))
956 (when (equal next
(car (last this
)))
957 (map-matching-directories
959 (make-pathname :directory
(append this rest
)
960 :defaults pathname
)))
961 (map-wild-inferiors function more pathname
)))))
967 ;;; Part of DIRECTORY: implements iterating over entries in a directory, and
969 (defun map-matching-entries (function directory match-name match-type
)
972 (when (and (funcall match-name
(pathname-name file
))
973 (funcall match-type
(pathname-type file
)))
974 (funcall function file
)))
977 :directories
:as-files
980 ;;; NOTE: There is a fair amount of hair below that is probably not
981 ;;; strictly necessary.
983 ;;; The issue is the following: what does (DIRECTORY "SYS:*;") mean?
984 ;;; Until 2004-01, SBCL's behaviour was unquestionably wrong, as it
985 ;;; did not translate the logical pathname at all, but instead treated
986 ;;; it as a physical one. Other Lisps seem to to treat this call as
987 ;;; equivalent to (DIRECTORY (TRANSLATE-LOGICAL-PATHNAME "SYS:*;")),
988 ;;; which is fine as far as it goes, but not very interesting, and
989 ;;; arguably counterintuitive. (PATHNAME-MATCH-P "SYS:SRC;" "SYS:*;")
990 ;;; is true, so why should "SYS:SRC;" not show up in the call to
991 ;;; DIRECTORY? (assuming the physical pathname corresponding to it
992 ;;; exists, of course).
994 ;;; So, the interpretation that I am pushing is for all pathnames
995 ;;; matching the input pathname to be queried. This means that we
996 ;;; need to compute the intersection of the input pathname and the
997 ;;; logical host FROM translations, and then translate the resulting
998 ;;; pathname using the host to the TO translation; this treatment is
999 ;;; recursively invoked until we get a physical pathname, whereupon
1000 ;;; our physical DIRECTORY implementation takes over.
1002 ;;; FIXME: this is an incomplete implementation. It only works when
1003 ;;; both are logical pathnames (which is OK, because that's the only
1004 ;;; case when we call it), but there are other pitfalls as well: see
1005 ;;; the DIRECTORY-HELPER below for some, but others include a lack of
1006 ;;; pattern handling.
1008 ;;; The above was written by CSR, I (RMK) believe. The argument that
1009 ;;; motivates the interpretation is faulty, however: PATHNAME-MATCH-P
1010 ;;; returns true for (PATHNAME-MATCH-P #P"/tmp/*/" #P"/tmp/../"), but
1011 ;;; the latter pathname is not in the result of DIRECTORY on the
1012 ;;; former. Indeed, if DIRECTORY were constrained to return the
1013 ;;; truename for every pathname for which PATHNAME-MATCH-P returned
1014 ;;; true and which denoted a filename that named an existing file,
1015 ;;; (DIRECTORY #P"/tmp/**/") would be required to list every file on a
1016 ;;; Unix system, since any file can be named as though it were "below"
1017 ;;; /tmp, given the dotdot entries. So I think the strongest
1018 ;;; "consistency" we can define between PATHNAME-MATCH-P and DIRECTORY
1019 ;;; is that PATHNAME-MATCH-P returns true of everything DIRECTORY
1020 ;;; returns, but not vice versa.
1022 ;;; In any case, even if the motivation were sound, DIRECTORY on a
1023 ;;; wild logical pathname has no portable semantics. I see nothing in
1024 ;;; ANSI that requires implementations to support wild physical
1025 ;;; pathnames, and so there need not be any translation of a wild
1026 ;;; logical pathname to a phyiscal pathname. So a program that calls
1027 ;;; DIRECTORY on a wild logical pathname is doing something
1028 ;;; non-portable at best. And if the only sensible semantics for
1029 ;;; DIRECTORY on a wild logical pathname is something like the
1030 ;;; following, it would be just as well if it signaled an error, since
1031 ;;; a program can't possibly rely on the result of an intersection of
1032 ;;; user-defined translations with a file system probe. (Potentially
1033 ;;; useful kinds of "pathname" that might not support wildcards could
1034 ;;; include pathname hosts that model unqueryable namespaces like HTTP
1035 ;;; URIs, or that model namespaces that it's not convenient to
1036 ;;; investigate, such as the namespace of TCP ports that some network
1037 ;;; host listens on. I happen to think it a bad idea to try to
1038 ;;; shoehorn such namespaces into a pathnames system, but people
1039 ;;; sometimes claim to want pathnames for these things.) -- RMK
1042 (defun pathname-intersections (one two
)
1043 (aver (logical-pathname-p one
))
1044 (aver (logical-pathname-p two
))
1046 ((intersect-version (one two
)
1047 (aver (typep one
'(or null
(member :newest
:wild
:unspecific
)
1049 (aver (typep two
'(or null
(member :newest
:wild
:unspecific
)
1052 ((eq one
:wild
) two
)
1053 ((eq two
:wild
) one
)
1054 ((or (null one
) (eq one
:unspecific
)) two
)
1055 ((or (null two
) (eq two
:unspecific
)) one
)
1058 (intersect-name/type
(one two
)
1059 (aver (typep one
'(or null
(member :wild
:unspecific
) string
)))
1060 (aver (typep two
'(or null
(member :wild
:unspecific
) string
)))
1062 ((eq one
:wild
) two
)
1063 ((eq two
:wild
) one
)
1064 ((or (null one
) (eq one
:unspecific
)) two
)
1065 ((or (null two
) (eq two
:unspecific
)) one
)
1066 ((string= one two
) one
)
1067 (t (return-from pathname-intersections nil
))))
1068 (intersect-directory (one two
)
1069 (aver (typep one
'(or null
(member :wild
:unspecific
) list
)))
1070 (aver (typep two
'(or null
(member :wild
:unspecific
) list
)))
1072 ((eq one
:wild
) two
)
1073 ((eq two
:wild
) one
)
1074 ((or (null one
) (eq one
:unspecific
)) two
)
1075 ((or (null two
) (eq two
:unspecific
)) one
)
1076 (t (aver (eq (car one
) (car two
)))
1078 (lambda (x) (cons (car one
) x
))
1079 (intersect-directory-helper (cdr one
) (cdr two
)))))))
1080 (let ((version (intersect-version
1081 (pathname-version one
) (pathname-version two
)))
1082 (name (intersect-name/type
1083 (pathname-name one
) (pathname-name two
)))
1084 (type (intersect-name/type
1085 (pathname-type one
) (pathname-type two
)))
1086 (host (pathname-host one
)))
1088 (make-pathname :host host
:name name
:type type
1089 :version version
:directory d
))
1090 (intersect-directory
1091 (pathname-directory one
) (pathname-directory two
))))))
1093 ;;; FIXME: written as its own function because I (CSR) don't
1094 ;;; understand it, so helping both debuggability and modularity. In
1095 ;;; case anyone is motivated to rewrite it, it returns a list of
1096 ;;; sublists representing the intersection of the two input directory
1097 ;;; paths (excluding the initial :ABSOLUTE or :RELATIVE).
1099 ;;; FIXME: Does not work with :UP or :BACK
1100 ;;; FIXME: Does not work with patterns
1102 ;;; FIXME: PFD suggests replacing this implementation with a DFA
1103 ;;; conversion of a NDFA. Find out (a) what this means and (b) if it
1104 ;;; turns out to be worth it.
1105 (defun intersect-directory-helper (one two
)
1106 (flet ((simple-intersection (cone ctwo
)
1108 ((eq cone
:wild
) ctwo
)
1109 ((eq ctwo
:wild
) cone
)
1110 (t (aver (typep cone
'string
))
1111 (aver (typep ctwo
'string
))
1112 (if (string= cone ctwo
) cone nil
)))))
1114 ((loop-possible-wild-inferiors-matches
1115 (lower-bound bounding-sequence order
)
1116 (let ((index (gensym)) (g2 (gensym)) (g3 (gensym)) (l (gensym)))
1117 `(let ((,l
(length ,bounding-sequence
)))
1118 (loop for
,index from
,lower-bound to
,l
1119 append
(mapcar (lambda (,g2
)
1121 (butlast ,bounding-sequence
(- ,l
,index
))
1126 (if (eq (car (nthcdr ,index
,bounding-sequence
))
1130 (intersect-directory-helper
1132 `((nthcdr ,index one
) (cdr two
))
1133 `((cdr one
) (nthcdr ,index two
)))))))))))
1135 ((and (eq (car one
) :wild-inferiors
)
1136 (eq (car two
) :wild-inferiors
))
1138 (append (mapcar (lambda (x) (cons :wild-inferiors x
))
1139 (intersect-directory-helper (cdr one
) (cdr two
)))
1140 (loop-possible-wild-inferiors-matches 2 one t
)
1141 (loop-possible-wild-inferiors-matches 2 two nil
))
1143 ((eq (car one
) :wild-inferiors
)
1144 (delete-duplicates (loop-possible-wild-inferiors-matches 0 two nil
)
1146 ((eq (car two
) :wild-inferiors
)
1147 (delete-duplicates (loop-possible-wild-inferiors-matches 0 one t
)
1149 ((and (null one
) (null two
)) (list nil
))
1152 (t (and (simple-intersection (car one
) (car two
))
1153 (mapcar (lambda (x) (cons (simple-intersection
1154 (car one
) (car two
)) x
))
1155 (intersect-directory-helper (cdr one
) (cdr two
)))))))))
1158 (defun directory-pathname-p (pathname)
1159 (and (pathnamep pathname
)
1160 (null (pathname-name pathname
))
1161 (null (pathname-type pathname
))))
1163 (defun ensure-directories-exist (pathspec &key verbose
(mode #o777
))
1164 "Test whether the directories containing the specified file
1165 actually exist, and attempt to create them if they do not.
1166 The MODE argument is a CMUCL/SBCL-specific extension to control
1167 the Unix permission bits."
1168 (let ((pathname (physicalize-pathname (merge-pathnames (pathname pathspec
))))
1170 (when (wild-pathname-p pathname
)
1171 (error 'simple-file-error
1172 :format-control
"bad place for a wild pathname"
1173 :pathname pathspec
))
1174 (let* ((dir (pathname-directory pathname
))
1175 (*default-pathname-defaults
*
1176 (make-pathname :directory dir
:device
(pathname-device pathname
)))
1177 (dev (pathname-device pathname
)))
1178 (loop for i from
(case dev
(:unc
3) (otherwise 2))
1181 (let* ((newpath (make-pathname
1182 :host
(pathname-host pathname
)
1184 :directory
(subseq dir
0 i
)))
1185 (probed (probe-file newpath
)))
1186 (unless (directory-pathname-p probed
)
1187 (let ((namestring (coerce (native-namestring newpath
)
1190 (format *standard-output
*
1191 "~&creating directory: ~A~%"
1193 (sb!unix
:unix-mkdir namestring mode
)
1194 (unless (directory-pathname-p (probe-file newpath
))
1201 (not (directory-pathname-p probed
)))
1202 "Can't create directory ~A,~
1203 ~%a file with the same name already exists."
1204 "Can't create directory ~A")
1205 :format-arguments
(list namestring
))
1207 :report
"Retry directory creation."
1208 (ensure-directories-exist
1210 :verbose verbose
:mode mode
))
1213 "Continue as if directory creation was successful."
1215 (setf created-p t
)))))
1216 (values pathspec created-p
))))
1218 (/show0
"filesys.lisp 1000")