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
)
56 "Remove any occurrences of escape characters from the string
57 because we've already checked for whatever they may have
59 (declare (type simple-string namestr
)
60 (type index start end
))
61 (let* ((result (make-string (- end start
) :element-type
'character
))
64 (do ((src start
(1+ src
)))
67 (setf (schar result dst
) (schar namestr src
))
71 (let ((char (schar namestr src
)))
72 (cond ((char= char escape-char
)
75 (setf (schar result dst
) char
)
78 (error 'namestring-parse-error
79 :complaint
"escape char in a bad place"
82 (%shrink-vector result dst
)))
84 (defun maybe-make-pattern (namestr start end escape-char
)
85 (declare (type simple-string namestr
)
86 (type index start end
)
87 (type character escape-char
))
91 (last-regular-char nil
)
93 (flet ((flush-pending-regulars ()
94 (when last-regular-char
95 (pattern (if any-quotes
96 (remove-escape-characters
97 namestr last-regular-char
99 (subseq namestr last-regular-char index
)))
100 (setf any-quotes nil
)
101 (setf last-regular-char nil
))))
105 (let ((char (schar namestr index
)))
109 ((char= char escape-char
)
112 (unless last-regular-char
113 (setf last-regular-char index
))
116 (flush-pending-regulars)
117 (pattern :single-char-wild
)
120 (flush-pending-regulars)
121 (pattern :multi-char-wild
)
124 (flush-pending-regulars)
126 (position #\
] namestr
:start index
:end end
)))
127 (unless close-bracket
128 (error 'namestring-parse-error
129 :complaint
"#\\[ with no corresponding #\\]"
132 (pattern (cons :character-set
136 (setf index
(1+ close-bracket
))))
138 (unless last-regular-char
139 (setf last-regular-char index
))
141 (flush-pending-regulars)))
142 (cond ((null (pattern))
144 ((null (cdr (pattern)))
145 (let ((piece (first (pattern))))
147 ((member :multi-char-wild
) :wild
)
148 (simple-string piece
)
150 (make-pattern (pattern))))))
152 (make-pattern (pattern))))))
154 (defun unparse-physical-piece (thing escape-char
)
158 (let* ((srclen (length thing
))
161 (let ((char (schar thing i
)))
165 (t (when (char= char escape-char
)
167 (let ((result (make-string dstlen
))
169 (dotimes (src srclen
)
170 (let ((char (schar thing src
)))
173 (setf (schar result dst
) escape-char
)
175 (t (when (char= char escape-char
)
176 (setf (schar result dst
) escape-char
)
178 (setf (schar result dst
) char
)
182 (with-simple-output-to-string (s)
183 (dolist (piece (pattern-pieces thing
))
186 (write-string piece s
))
190 (write-string "*" s
))
192 (write-string "?" s
))))
197 (write-string (cdr piece
) s
)
198 (write-string "]" s
))
200 (error "invalid pattern piece: ~S" piece
))))))))))
202 (defun make-matcher (piece)
203 (cond ((eq piece
:wild
)
205 ((typep piece
'pattern
)
207 (when (stringp other
)
208 (pattern-matches piece other
))))
211 (equal piece other
)))))
213 (/show0
"filesys.lisp 160")
215 (defun extract-name-type-and-version (namestr start end escape-char
)
216 (declare (type simple-string namestr
)
217 (type index start end
))
218 (let* ((last-dot (position #\. namestr
:start
(1+ start
) :end end
222 (values (maybe-make-pattern namestr start last-dot escape-char
)
223 (maybe-make-pattern namestr
(1+ last-dot
) end escape-char
)
226 (values (maybe-make-pattern namestr start end escape-char
)
230 (/show0
"filesys.lisp 200")
233 ;;;; Grabbing the kind of file when we have a namestring.
234 (defun native-file-kind (namestring)
235 (multiple-value-bind (existsp errno ino mode
)
237 (sb!unix
:unix-lstat namestring
)
239 (sb!unix
:unix-stat namestring
)
240 (declare (ignore errno ino
))
242 (let ((ifmt (logand mode sb
!unix
:s-ifmt
)))
244 (#.sb
!unix
:s-ifreg
:file
)
245 (#.sb
!unix
:s-ifdir
:directory
)
247 (#.sb
!unix
:s-iflnk
:symlink
)
250 ;;;; TRUENAME, PROBE-FILE, FILE-AUTHOR, FILE-WRITE-DATE.
252 ;;; Rewritten in 12/2007 by RMK, replacing 13+ year old CMU code that
253 ;;; made a mess of things in order to support search lists (which SBCL
254 ;;; has never had). These are now all relatively straightforward
255 ;;; wrappers around stat(2) and realpath(2), with the same basic logic
256 ;;; in all cases. The wrinkles to be aware of:
258 ;;; * SBCL defines the truename of an existing, dangling or
259 ;;; self-referring symlink to be the symlink itself.
260 ;;; * The old version of PROBE-FILE merged the pathspec against
261 ;;; *DEFAULT-PATHNAME-DEFAULTS* twice, and so lost when *D-P-D*
262 ;;; was a relative pathname. Even if the case where *D-P-D* is a
263 ;;; relative pathname is problematic, there's no particular reason
264 ;;; to get that wrong, so let's try not to.
265 ;;; * Note that while stat(2) is probably atomic, getting the truename
266 ;;; for a filename involves poking all over the place, and so is
267 ;;; subject to race conditions if other programs mutate the file
268 ;;; system while we're resolving symlinks. So it's not implausible for
269 ;;; realpath(3) to fail even if stat(2) succeeded. There's nothing
270 ;;; obvious we can do about this, however.
271 ;;; * Windows' apparent analogue of realpath(3) is called
272 ;;; GetFullPathName, and it's a bit less useful than realpath(3).
273 ;;; In particular, while realpath(3) errors in case the file doesn't
274 ;;; exist, GetFullPathName seems to return a filename in all cases.
275 ;;; As realpath(3) is not atomic anyway, we only ever call it when
276 ;;; we think a file exists, so just be careful when rewriting this
279 ;;; Given a pathname designator, some quality to query for, return one
280 ;;; of a pathname, a universal time, or a string (a file-author), or
281 ;;; NIL. QUERY-FOR may be one of :TRUENAME, :EXISTENCE, :WRITE-DATE,
282 ;;; :AUTHOR. If ERRORP is false, return NIL in case the file system
283 ;;; returns an error code; otherwise, signal an error. Accepts
284 ;;; logical pathnames, too (but never returns LPNs). For internal
286 (defun query-file-system (pathspec query-for
&optional
(errorp t
))
287 (let ((pathname (translate-logical-pathname
290 (sane-default-pathname-defaults)))))
291 (when (wild-pathname-p pathname
)
292 (error 'simple-file-error
294 :format-control
"~@<can't find the ~A of wild pathname ~A~
295 (physicalized from ~A).~:>"
296 :format-arguments
(list query-for pathname pathspec
)))
297 (macrolet ((fail (note-format pathname errno
)
298 ;; Do this as a macro to avoid evaluating format
299 ;; calls when ERROP is NIL
301 (simple-file-perror ,note-format
,pathname
,errno
)
302 (return-from query-file-system nil
))))
303 (let ((filename (native-namestring pathname
:as-file t
)))
306 ((:existence
:truename
)
307 (multiple-value-bind (file kind
)
308 (sb!win32
::native-probe-file-name filename
)
309 (when (and (not file
) kind
)
310 (setf file filename
))
311 ;; The following OR was an AND, but that breaks files like NUL,
312 ;; for which GetLongPathName succeeds yet GetFileAttributesEx
313 ;; fails to return the file kind. --DFL
316 (parse-native-namestring
318 (pathname-host pathname
)
319 (sane-default-pathname-defaults)
320 :as-directory
(eq :directory kind
)))
321 (fail (format nil
"Failed to find the ~A of ~~A" query-for
) filename
322 (sb!win32
:get-last-error
)))))
324 (or (sb!win32
::native-file-write-date filename
)
325 (fail (format nil
"Failed to find the ~A of ~~A" query-for
) filename
326 (sb!win32
:get-last-error
)))))
328 (multiple-value-bind (existsp errno ino mode nlink uid gid rdev size
330 (sb!unix
:unix-stat filename
)
331 (declare (ignore ino nlink gid rdev size atime
))
332 (labels ((parse (filename &key
(as-directory
337 (parse-native-namestring
339 (pathname-host pathname
)
340 (sane-default-pathname-defaults)
341 :as-directory as-directory
)))
342 (resolve-problematic-symlink (&optional realpath-failed
)
343 ;; SBCL has for many years had a policy that a pathname
344 ;; that names an existing, dangling or self-referential
345 ;; symlink denotes the symlink itself. stat(2) fails
346 ;; and sets errno to ENOENT or ELOOP respectively, but
347 ;; we must distinguish cases where the symlink exists
348 ;; from ones where there's a loop in the apparent
349 ;; containing directory.
350 ;; Also handles symlinks in /proc/pid/fd/ to
351 ;; pipes or sockets on Linux
352 (multiple-value-bind (linkp ignore ino mode nlink uid gid rdev
354 (sb!unix
:unix-lstat filename
)
355 (declare (ignore ignore ino mode nlink gid rdev size atime
))
356 (when (and (or (= errno sb
!unix
:enoent
)
357 (= errno sb
!unix
:eloop
)
360 (return-from query-file-system
363 ;; We do this reparse so as to return a
364 ;; normalized pathname.
365 (parse filename
:as-directory nil
))
367 ;; So here's a trick: since lstat succeded,
368 ;; FILENAME exists, so its directory exists and
369 ;; only the non-directory part is loopy. So
370 ;; let's resolve FILENAME's directory part with
371 ;; realpath(3), in order to get a canonical
372 ;; absolute name for the directory, and then
373 ;; return a pathname having PATHNAME's name,
374 ;; type, and version, but the rest from the
375 ;; truename of the directory. Since we turned
376 ;; PATHNAME into FILENAME "as a file", FILENAME
377 ;; does not end in a slash, and so we get the
378 ;; directory part of FILENAME by reparsing
379 ;; FILENAME and masking off its name, type, and
380 ;; version bits. But note not to call ourselves
381 ;; recursively, because we don't want to
382 ;; re-merge against *DEFAULT-PATHNAME-DEFAULTS*,
383 ;; since PATHNAME may be a relative pathname.
386 (multiple-value-bind (realpath errno
)
387 (sb!unix
:unix-realpath
393 :defaults
(parse filename
394 :as-directory nil
))))
396 (fail "couldn't resolve ~A" filename errno
)))
398 (if (directory-pathname-p pathname
)
399 (parse (car (last (pathname-directory pathname
)))
402 (:author
(sb!unix
:uid-username uid
))
403 (:write-date
(+ unix-to-universal-time mtime
))))))
404 ;; If we're still here, the file doesn't exist; error.
406 (format nil
"Failed to find the ~A of ~~A" query-for
)
410 (:existence
(parse filename
))
412 ;; Note: in case the file is stat'able, POSIX
413 ;; realpath(3) gets us a canonical absolute
414 ;; filename, even if the post-merge PATHNAME
416 (parse (or (sb!unix
:unix-realpath filename
)
417 (resolve-problematic-symlink t
))))
418 (:author
(sb!unix
:uid-username uid
))
419 (:write-date
(+ unix-to-universal-time mtime
)))
420 (resolve-problematic-symlink))))))))
423 (defun probe-file (pathspec)
425 "Return the truename of PATHSPEC if the truename can be found,
426 or NIL otherwise. See TRUENAME for more information."
427 (query-file-system pathspec
:truename nil
))
429 (defun truename (pathspec)
431 "If PATHSPEC is a pathname that names an existing file, return
432 a pathname that denotes a canonicalized name for the file. If
433 pathspec is a stream associated with a file, return a pathname
434 that denotes a canonicalized name for the file associated with
437 An error of type FILE-ERROR is signalled if no such file exists
438 or if the file system is such that a canonicalized file name
439 cannot be determined or if the pathname is wild.
441 Under Unix, the TRUENAME of a symlink that links to itself or to
442 a file that doesn't exist is considered to be the name of the
443 broken symlink itself."
444 ;; Note that eventually this routine might be different for streams
445 ;; than for other pathname designators.
446 (if (streamp pathspec
)
447 (query-file-system pathspec
:truename
)
448 (query-file-system pathspec
:truename
)))
450 (defun file-author (pathspec)
452 "Return the author of the file specified by PATHSPEC. Signal an
453 error of type FILE-ERROR if no such file exists, or if PATHSPEC
455 (query-file-system pathspec
:author
))
457 (defun file-write-date (pathspec)
459 "Return the write date of the file specified by PATHSPEC.
460 An error of type FILE-ERROR is signaled if no such file exists,
461 or if PATHSPEC is a wild pathname."
462 (query-file-system pathspec
:write-date
))
464 ;;;; miscellaneous other operations
466 (/show0
"filesys.lisp 700")
468 (defun rename-file (file new-name
)
470 "Rename FILE to have the specified NEW-NAME. If FILE is a stream open to a
471 file, then the associated file is renamed."
472 (let* ((original (merge-pathnames file
(sane-default-pathname-defaults)))
473 (old-truename (truename original
))
474 (original-namestring (native-namestring (physicalize-pathname original
)
476 (new-name (merge-pathnames new-name original
))
477 (new-namestring (native-namestring (physicalize-pathname new-name
)
479 (unless new-namestring
480 (error 'simple-file-error
482 :format-control
"~S can't be created."
483 :format-arguments
(list new-name
)))
484 (multiple-value-bind (res error
)
485 (sb!unix
:unix-rename original-namestring new-namestring
)
487 (error 'simple-file-error
489 :format-control
"~@<couldn't rename ~2I~_~A ~I~_to ~2I~_~A: ~
491 :format-arguments
(list original new-name
(strerror error
))))
493 (file-name file new-name
))
494 (values new-name old-truename
(truename new-name
)))))
496 (defun delete-file (file)
498 "Delete the specified FILE.
500 If FILE is a stream, on Windows the stream is closed immediately. On Unix
501 platforms the stream remains open, allowing IO to continue: the OS resources
502 associated with the deleted file remain available till the stream is closed as
503 per standard Unix unlink() behaviour."
504 (let* ((pathname (translate-logical-pathname
505 (merge-pathnames file
(sane-default-pathname-defaults))))
506 (namestring (native-namestring pathname
:as-file t
)))
510 (multiple-value-bind (res err
)
511 #!-win32
(sb!unix
:unix-unlink namestring
)
512 #!+win32
(or (sb!win32
::native-delete-file namestring
)
513 (values nil
(sb!win32
:get-last-error
)))
515 (simple-file-perror "couldn't delete ~A" namestring err
))))
518 (defun directorize-pathname (pathname)
519 (if (or (pathname-name pathname
)
520 (pathname-type pathname
))
521 (make-pathname :directory
(append (pathname-directory pathname
)
522 (list (file-namestring pathname
)))
523 :host
(pathname-host pathname
)
524 :device
(pathname-device pathname
))
527 (defun delete-directory (pathspec &key recursive
)
529 "Deletes the directory designated by PATHSPEC (a pathname designator).
530 Returns the truename of the directory deleted.
532 If RECURSIVE is false \(the default), signals an error unless the directory is
533 empty. If RECURSIVE is true, first deletes all files and subdirectories. If
534 RECURSIVE is true and the directory contains symbolic links, the links are
535 deleted, not the files and directories they point to.
537 Signals an error if PATHSPEC designates a file or a symbolic link instead of a
538 directory, or if the directory could not be deleted for any reason.
542 \(DELETE-DIRECTORY \"/tmp/foo\")
543 \(DELETE-DIRECTORY \"/tmp/foo/\")
545 delete the \"foo\" subdirectory of \"/tmp\", or signal an error if it does not
546 exist or if is a file or a symbolic link."
547 (declare (type pathname-designator pathspec
))
548 (let ((physical (directorize-pathname
549 (physicalize-pathname
551 pathspec
(sane-default-pathname-defaults))))))
552 (labels ((recurse-merged (dir)
554 (recurse (merge-pathnames sub dir
))))
557 (delete-file (merge-pathnames file dir
))))
559 (map-directory (recurse-merged dir
) dir
562 :classify-symlinks nil
)
563 (map-directory (delete-merged dir
) dir
566 :classify-symlinks nil
)
569 (let ((namestring (native-namestring dir
:as-file t
)))
570 (multiple-value-bind (res errno
)
572 (or (sb!win32
::native-delete-directory namestring
)
573 (values nil
(sb!win32
:get-last-error
)))
576 (not (minusp (alien-funcall
577 (extern-alien "rmdir"
578 (function int c-string
))
584 "Could not delete directory ~A"
585 namestring errno
))))))
588 (delete-dir physical
)))))
591 (defun sbcl-homedir-pathname ()
592 (let ((sbcl-home (posix-getenv "SBCL_HOME")))
593 ;; SBCL_HOME isn't set for :EXECUTABLE T embedded cores
594 (when (and sbcl-home
(not (string= sbcl-home
"")))
595 (parse-native-namestring sbcl-home
597 *default-pathname-defaults
*
600 (defun user-homedir-namestring (&optional username
)
601 (flet ((not-empty (x)
602 (and (not (equal x
"")) x
)))
604 (sb!unix
:user-homedir username
)
605 (or (not-empty (posix-getenv "HOME"))
607 (not-empty (posix-getenv "USERPROFILE"))
609 (let ((drive (not-empty (posix-getenv "HOMEDRIVE")))
610 (path (not-empty (posix-getenv "HOMEPATH"))))
612 (concatenate 'string drive path
)))
614 (not-empty (sb!unix
:uid-homedir
(sb!unix
:unix-getuid
)))
615 (error "Couldn't find home directory.")))))
617 ;;; (This is an ANSI Common Lisp function.)
618 (defun user-homedir-pathname (&optional host
)
620 "Return the home directory of the user as a pathname. If the HOME
621 environment variable has been specified, the directory it designates
622 is returned; otherwise obtains the home directory from the operating
623 system. HOST argument is ignored by SBCL."
624 (declare (ignore host
))
626 (parse-native-namestring
627 (or (user-homedir-namestring)
629 (sb!win32
::get-folder-namestring sb
!win32
::csidl_profile
))
631 *default-pathname-defaults
*
637 (defun directory (pathspec &key
(resolve-symlinks t
))
639 "Return a list of PATHNAMEs, each the TRUENAME of a file that matched the
640 given pathname. Note that the interaction between this ANSI-specified
641 TRUENAMEing and the semantics of the Unix filesystem (symbolic links..) means
642 this function can sometimes return files which don't have the same directory
643 as PATHNAME. If :RESOLVE-SYMLINKS is NIL, don't resolve symbolic links in
645 (let (;; We create one entry in this hash table for each truename,
646 ;; as an asymptotically efficient way of removing duplicates
647 ;; (which can arise when e.g. multiple symlinks map to the
649 (truenames (make-hash-table :test
#'equal
)))
650 (labels ((record (pathname)
651 (let ((truename (if resolve-symlinks
652 ;; FIXME: Why not not TRUENAME? As reported by
653 ;; Milan Zamazal sbcl-devel 2003-10-05, using
654 ;; TRUENAME causes a race condition whereby
655 ;; removal of a file during the directory
656 ;; operation causes an error. It's not clear
657 ;; what the right thing to do is, though. --
659 (query-file-system pathname
:truename nil
)
660 (query-file-system pathname
:existence nil
))))
662 (setf (gethash (namestring truename
) truenames
)
664 (do-physical-pathnames (pathname)
665 (aver (not (logical-pathname-p pathname
)))
666 (let* (;; KLUDGE: Since we don't canonize pathnames on construction,
667 ;; we really have to do it here to get #p"foo/." mean the same
669 (pathname (canonicalize-pathname pathname
))
670 (name (pathname-name pathname
))
671 (type (pathname-type pathname
))
672 (match-name (make-matcher name
))
673 (match-type (make-matcher type
)))
674 (map-matching-directories
677 (map-matching-entries #'record
683 (do-pathnames (pathname)
684 (if (logical-pathname-p pathname
)
685 (let ((host (intern-logical-host (pathname-host pathname
))))
686 (dolist (x (logical-host-canon-transls host
))
687 (destructuring-bind (from to
) x
689 (pathname-intersections pathname from
)))
690 (dolist (p intersections
)
691 (do-pathnames (translate-pathname p from to
)))))))
692 (do-physical-pathnames pathname
))))
693 (declare (truly-dynamic-extent #'record
))
694 (do-pathnames (merge-pathnames pathspec
)))
696 ;; Sorting isn't required by the ANSI spec, but sorting into some
697 ;; canonical order seems good just on the grounds that the
698 ;; implementation should have repeatable behavior when possible.
699 (sort (loop for namestring being each hash-key in truenames
700 using
(hash-value truename
)
701 collect
(cons namestring truename
))
705 (defun canonicalize-pathname (pathname)
706 ;; We're really only interested in :UNSPECIFIC -> NIL, :BACK and :UP,
707 ;; and dealing with #p"foo/.." and #p"foo/."
708 (labels ((simplify (piece)
709 (unless (eq :unspecific piece
)
711 (canonicalize-directory (directory)
713 (dolist (piece directory
)
715 ((and pieces
(member piece
'(:back
:up
)))
716 ;; FIXME: We should really canonicalize when we construct
717 ;; pathnames. This is just wrong.
719 ((:absolute
:wild-inferiors
)
720 (error 'simple-file-error
721 :format-control
"Invalid use of ~S after ~S."
722 :format-arguments
(list piece
(car pieces
))
724 ((:relative
:up
:back
)
729 ;; This case only really matters on Windows,
730 ;; because on POSIX, our call site (TRUENAME via
731 ;; QUERY-FILE-SYSTEM) only passes in pathnames from
732 ;; realpath(3), in which /./ has been removed
733 ;; already. Windows, however, depends on us to
734 ;; perform this fixup. -- DFL
737 (push piece pieces
))))
739 (let ((name (simplify (pathname-name pathname
)))
740 (type (simplify (pathname-type pathname
)))
741 (dir (canonicalize-directory (pathname-directory pathname
))))
742 (cond ((equal "." name
)
744 (make-pathname :name nil
:defaults pathname
))
746 (make-pathname :name nil
748 :directory
(butlast dir
)
749 :defaults pathname
))))
751 (make-pathname :name name
:type type
753 :defaults pathname
))))))
755 ;;; Given a native namestring, provides a WITH-HASH-TABLE-ITERATOR style
756 ;;; interface to mapping over namestrings of entries in the corresponding
758 (defmacro with-native-directory-iterator
((iterator namestring
&key errorp
) &body body
)
759 (with-unique-names (one-iter)
761 ((iterate (,one-iter
)
762 (declare (type function
,one-iter
))
763 (macrolet ((,iterator
()
764 `(funcall ,',one-iter
)))
767 (sb!win32
::native-call-with-directory-iterator
768 #'iterate
,namestring
,errorp
)
770 (call-with-native-directory-iterator #'iterate
,namestring
,errorp
))))
772 (defun call-with-native-directory-iterator (function namestring errorp
)
773 (declare (type (or null string
) namestring
)
781 (let ((ent (sb!unix
:unix-readdir dp nil
)))
783 (let ((name (sb!unix
:unix-dirent-name ent
)))
785 (cond ((equal "." name
)
790 (return-from one-iter name
))))))))))
793 (setf dp
(sb!unix
:unix-opendir namestring errorp
))
795 (funcall function
#'one-iter
)))
797 (sb!unix
:unix-closedir dp nil
)))))))
799 ;;; This is our core directory access interface that we use to implement
801 (defun map-directory (function directory
&key
(files t
) (directories t
)
802 (classify-symlinks t
) (errorp t
))
804 "Map over entries in DIRECTORY. Keyword arguments specify which entries to
808 If true, call FUNCTION with the pathname of each file in DIRECTORY.
812 If true, call FUNCTION with a pathname for each subdirectory of DIRECTORY.
813 If :AS-FILES, the pathname used is a pathname designating the subdirectory
814 as a file in DIRECTORY. Otherwise the pathname used is a directory
815 pathname. Defaults to T.
818 If true, the decision to call FUNCTION with the pathname of a symbolic link
819 depends on the resolution of the link: if it points to a directory, it is
820 considered a directory entry, otherwise a file entry. If false, all
821 symbolic links are considered file entries. In both cases the pathname used
822 for the symbolic link is not fully resolved, but names it as an immediate
823 child of DIRECTORY. Defaults to T.
826 If true, signal an error if DIRECTORY does not exist, cannot be read, etc.
829 Experimental: interface subject to change."
830 (declare (pathname-designator directory
))
831 (let* ((fun (%coerce-callable-to-fun function
))
832 (as-files (eq :as-files directories
))
833 (physical (physicalize-pathname directory
))
834 (realname (query-file-system physical
:existence nil
))
835 (canonical (if realname
836 (parse-native-namestring realname
837 (pathname-host physical
)
838 (sane-default-pathname-defaults)
840 (return-from map-directory nil
)))
841 (dirname (native-namestring canonical
)))
842 (flet ((map-it (name dirp
)
844 (merge-pathnames (parse-native-namestring
846 :as-directory
(and dirp
(not as-files
)))
848 (with-native-directory-iterator (next dirname
:errorp errorp
)
850 ;; provision for FindFirstFileExW-based iterator that should be used
851 ;; on Windows: file kind is known instantly there, so we'll have it
852 ;; returned by (next) soon.
853 (multiple-value-bind (name kind
) (next)
854 (unless (or name kind
) (return))
856 (setf kind
(native-file-kind
857 (concatenate 'string dirname name
))))
864 (if classify-symlinks
865 (let* ((tmpname (merge-pathnames
866 (parse-native-namestring
867 name nil physical
:as-directory nil
)
869 (truename (query-file-system tmpname
:truename nil
)))
870 (if (or (not truename
)
871 (or (pathname-name truename
) (pathname-type truename
)))
873 (funcall fun tmpname
))
879 ;; Anything else parses as a file.
881 (map-it name nil
)))))))))))
883 ;;; Part of DIRECTORY: implements matching the directory spec. Calls FUNCTION
884 ;;; with all DIRECTORIES that match the directory portion of PATHSPEC.
885 (defun map-matching-directories (function pathspec
)
886 (let* ((dir (pathname-directory pathspec
))
887 (length (length dir
))
888 (wild (position-if (lambda (elt)
889 (or (eq :wild elt
) (typep elt
'pattern
)))
891 (wild-inferiors (position :wild-inferiors dir
))
892 (end (cond ((and wild wild-inferiors
)
893 (min wild wild-inferiors
))
895 (or wild wild-inferiors length
))))
896 (rest (subseq dir end
))
897 (starting-point (make-pathname :directory
(subseq dir
0 end
)
898 :device
(pathname-device pathspec
)
899 :host
(pathname-host pathspec
)
903 (cond (wild-inferiors
904 (map-wild-inferiors function rest starting-point
))
906 (map-wild function rest starting-point
))
908 ;; Nothing wild -- the directory matches itself.
909 (funcall function starting-point
))))
912 (defun last-directory-piece (pathname)
913 (car (last (pathname-directory pathname
))))
915 ;;; Part of DIRECTORY: implements iterating over a :WILD or pattern component
916 ;;; in the directory spec.
917 (defun map-wild (function more directory
)
918 (let ((this (pop more
))
920 (flet ((cont (subdirectory)
923 (funcall function subdirectory
))
924 ((or (eq :wild next
) (typep next
'pattern
))
925 (map-wild function more subdirectory
))
926 ((eq :wild-inferiors next
)
927 (map-wild-inferiors function more subdirectory
))
929 (let ((this (pathname-directory subdirectory
)))
930 (map-matching-directories
932 (make-pathname :directory
(append this more
)
933 :defaults subdirectory
)))))))
938 (when (pattern-matches this
(last-directory-piece sub
))
939 (funcall #'cont sub
))))
945 ;;; Part of DIRECTORY: implements iterating over a :WILD-INFERIORS component
946 ;;; in the directory spec.
947 (defun map-wild-inferiors (function more directory
)
948 (loop while
(member (car more
) '(:wild
:wild-inferiors
))
950 (let ((next (car more
))
953 (funcall function directory
))
957 (funcall function pathname
)
958 (map-wild-inferiors function more pathname
)))
961 (let ((this (pathname-directory pathname
)))
962 (when (equal next
(car (last this
)))
963 (map-matching-directories
965 (make-pathname :directory
(append this rest
)
966 :defaults pathname
)))
967 (map-wild-inferiors function more pathname
)))))
973 ;;; Part of DIRECTORY: implements iterating over entries in a directory, and
975 (defun map-matching-entries (function directory match-name match-type
)
978 (when (and (funcall match-name
(pathname-name file
))
979 (funcall match-type
(pathname-type file
)))
980 (funcall function file
)))
983 :directories
:as-files
986 ;;; NOTE: There is a fair amount of hair below that is probably not
987 ;;; strictly necessary.
989 ;;; The issue is the following: what does (DIRECTORY "SYS:*;") mean?
990 ;;; Until 2004-01, SBCL's behaviour was unquestionably wrong, as it
991 ;;; did not translate the logical pathname at all, but instead treated
992 ;;; it as a physical one. Other Lisps seem to to treat this call as
993 ;;; equivalent to (DIRECTORY (TRANSLATE-LOGICAL-PATHNAME "SYS:*;")),
994 ;;; which is fine as far as it goes, but not very interesting, and
995 ;;; arguably counterintuitive. (PATHNAME-MATCH-P "SYS:SRC;" "SYS:*;")
996 ;;; is true, so why should "SYS:SRC;" not show up in the call to
997 ;;; DIRECTORY? (assuming the physical pathname corresponding to it
998 ;;; exists, of course).
1000 ;;; So, the interpretation that I am pushing is for all pathnames
1001 ;;; matching the input pathname to be queried. This means that we
1002 ;;; need to compute the intersection of the input pathname and the
1003 ;;; logical host FROM translations, and then translate the resulting
1004 ;;; pathname using the host to the TO translation; this treatment is
1005 ;;; recursively invoked until we get a physical pathname, whereupon
1006 ;;; our physical DIRECTORY implementation takes over.
1008 ;;; FIXME: this is an incomplete implementation. It only works when
1009 ;;; both are logical pathnames (which is OK, because that's the only
1010 ;;; case when we call it), but there are other pitfalls as well: see
1011 ;;; the DIRECTORY-HELPER below for some, but others include a lack of
1012 ;;; pattern handling.
1014 ;;; The above was written by CSR, I (RMK) believe. The argument that
1015 ;;; motivates the interpretation is faulty, however: PATHNAME-MATCH-P
1016 ;;; returns true for (PATHNAME-MATCH-P #P"/tmp/*/" #P"/tmp/../"), but
1017 ;;; the latter pathname is not in the result of DIRECTORY on the
1018 ;;; former. Indeed, if DIRECTORY were constrained to return the
1019 ;;; truename for every pathname for which PATHNAME-MATCH-P returned
1020 ;;; true and which denoted a filename that named an existing file,
1021 ;;; (DIRECTORY #P"/tmp/**/") would be required to list every file on a
1022 ;;; Unix system, since any file can be named as though it were "below"
1023 ;;; /tmp, given the dotdot entries. So I think the strongest
1024 ;;; "consistency" we can define between PATHNAME-MATCH-P and DIRECTORY
1025 ;;; is that PATHNAME-MATCH-P returns true of everything DIRECTORY
1026 ;;; returns, but not vice versa.
1028 ;;; In any case, even if the motivation were sound, DIRECTORY on a
1029 ;;; wild logical pathname has no portable semantics. I see nothing in
1030 ;;; ANSI that requires implementations to support wild physical
1031 ;;; pathnames, and so there need not be any translation of a wild
1032 ;;; logical pathname to a phyiscal pathname. So a program that calls
1033 ;;; DIRECTORY on a wild logical pathname is doing something
1034 ;;; non-portable at best. And if the only sensible semantics for
1035 ;;; DIRECTORY on a wild logical pathname is something like the
1036 ;;; following, it would be just as well if it signaled an error, since
1037 ;;; a program can't possibly rely on the result of an intersection of
1038 ;;; user-defined translations with a file system probe. (Potentially
1039 ;;; useful kinds of "pathname" that might not support wildcards could
1040 ;;; include pathname hosts that model unqueryable namespaces like HTTP
1041 ;;; URIs, or that model namespaces that it's not convenient to
1042 ;;; investigate, such as the namespace of TCP ports that some network
1043 ;;; host listens on. I happen to think it a bad idea to try to
1044 ;;; shoehorn such namespaces into a pathnames system, but people
1045 ;;; sometimes claim to want pathnames for these things.) -- RMK
1048 (defun pathname-intersections (one two
)
1049 (aver (logical-pathname-p one
))
1050 (aver (logical-pathname-p two
))
1052 ((intersect-version (one two
)
1053 (aver (typep one
'(or null
(member :newest
:wild
:unspecific
)
1055 (aver (typep two
'(or null
(member :newest
:wild
:unspecific
)
1058 ((eq one
:wild
) two
)
1059 ((eq two
:wild
) one
)
1060 ((or (null one
) (eq one
:unspecific
)) two
)
1061 ((or (null two
) (eq two
:unspecific
)) one
)
1064 (intersect-name/type
(one two
)
1065 (aver (typep one
'(or null
(member :wild
:unspecific
) string
)))
1066 (aver (typep two
'(or null
(member :wild
:unspecific
) string
)))
1068 ((eq one
:wild
) two
)
1069 ((eq two
:wild
) one
)
1070 ((or (null one
) (eq one
:unspecific
)) two
)
1071 ((or (null two
) (eq two
:unspecific
)) one
)
1072 ((string= one two
) one
)
1073 (t (return-from pathname-intersections nil
))))
1074 (intersect-directory (one two
)
1075 (aver (typep one
'(or null
(member :wild
:unspecific
) list
)))
1076 (aver (typep two
'(or null
(member :wild
:unspecific
) list
)))
1078 ((eq one
:wild
) two
)
1079 ((eq two
:wild
) one
)
1080 ((or (null one
) (eq one
:unspecific
)) two
)
1081 ((or (null two
) (eq two
:unspecific
)) one
)
1082 (t (aver (eq (car one
) (car two
)))
1084 (lambda (x) (cons (car one
) x
))
1085 (intersect-directory-helper (cdr one
) (cdr two
)))))))
1086 (let ((version (intersect-version
1087 (pathname-version one
) (pathname-version two
)))
1088 (name (intersect-name/type
1089 (pathname-name one
) (pathname-name two
)))
1090 (type (intersect-name/type
1091 (pathname-type one
) (pathname-type two
)))
1092 (host (pathname-host one
)))
1094 (make-pathname :host host
:name name
:type type
1095 :version version
:directory d
))
1096 (intersect-directory
1097 (pathname-directory one
) (pathname-directory two
))))))
1099 ;;; FIXME: written as its own function because I (CSR) don't
1100 ;;; understand it, so helping both debuggability and modularity. In
1101 ;;; case anyone is motivated to rewrite it, it returns a list of
1102 ;;; sublists representing the intersection of the two input directory
1103 ;;; paths (excluding the initial :ABSOLUTE or :RELATIVE).
1105 ;;; FIXME: Does not work with :UP or :BACK
1106 ;;; FIXME: Does not work with patterns
1108 ;;; FIXME: PFD suggests replacing this implementation with a DFA
1109 ;;; conversion of a NDFA. Find out (a) what this means and (b) if it
1110 ;;; turns out to be worth it.
1111 (defun intersect-directory-helper (one two
)
1112 (flet ((simple-intersection (cone ctwo
)
1114 ((eq cone
:wild
) ctwo
)
1115 ((eq ctwo
:wild
) cone
)
1116 (t (aver (typep cone
'string
))
1117 (aver (typep ctwo
'string
))
1118 (if (string= cone ctwo
) cone nil
)))))
1120 ((loop-possible-wild-inferiors-matches
1121 (lower-bound bounding-sequence order
)
1122 (let ((index (gensym)) (g2 (gensym)) (g3 (gensym)) (l (gensym)))
1123 `(let ((,l
(length ,bounding-sequence
)))
1124 (loop for
,index from
,lower-bound to
,l
1125 append
(mapcar (lambda (,g2
)
1127 (butlast ,bounding-sequence
(- ,l
,index
))
1132 (if (eq (car (nthcdr ,index
,bounding-sequence
))
1136 (intersect-directory-helper
1138 `((nthcdr ,index one
) (cdr two
))
1139 `((cdr one
) (nthcdr ,index two
)))))))))))
1141 ((and (eq (car one
) :wild-inferiors
)
1142 (eq (car two
) :wild-inferiors
))
1144 (append (mapcar (lambda (x) (cons :wild-inferiors x
))
1145 (intersect-directory-helper (cdr one
) (cdr two
)))
1146 (loop-possible-wild-inferiors-matches 2 one t
)
1147 (loop-possible-wild-inferiors-matches 2 two nil
))
1149 ((eq (car one
) :wild-inferiors
)
1150 (delete-duplicates (loop-possible-wild-inferiors-matches 0 two nil
)
1152 ((eq (car two
) :wild-inferiors
)
1153 (delete-duplicates (loop-possible-wild-inferiors-matches 0 one t
)
1155 ((and (null one
) (null two
)) (list nil
))
1158 (t (and (simple-intersection (car one
) (car two
))
1159 (mapcar (lambda (x) (cons (simple-intersection
1160 (car one
) (car two
)) x
))
1161 (intersect-directory-helper (cdr one
) (cdr two
)))))))))
1164 (defun directory-pathname-p (pathname)
1165 (and (pathnamep pathname
)
1166 (null (pathname-name pathname
))
1167 (null (pathname-type pathname
))))
1169 (defun ensure-directories-exist (pathspec &key verbose
(mode #o777
))
1171 "Test whether the directories containing the specified file
1172 actually exist, and attempt to create them if they do not.
1173 The MODE argument is a CMUCL/SBCL-specific extension to control
1174 the Unix permission bits."
1175 (let ((pathname (physicalize-pathname (merge-pathnames (pathname pathspec
))))
1177 (when (wild-pathname-p pathname
)
1178 (error 'simple-file-error
1179 :format-control
"bad place for a wild pathname"
1180 :pathname pathspec
))
1181 (let* ((dir (pathname-directory pathname
))
1182 (*default-pathname-defaults
*
1183 (make-pathname :directory dir
:device
(pathname-device pathname
)))
1184 (dev (pathname-device pathname
)))
1185 (loop for i from
(case dev
(:unc
3) (otherwise 2))
1188 (let* ((newpath (make-pathname
1189 :host
(pathname-host pathname
)
1191 :directory
(subseq dir
0 i
)))
1192 (probed (probe-file newpath
)))
1193 (unless (directory-pathname-p probed
)
1194 (let ((namestring (coerce (native-namestring newpath
)
1197 (format *standard-output
*
1198 "~&creating directory: ~A~%"
1200 (sb!unix
:unix-mkdir namestring mode
)
1201 (unless (directory-pathname-p (probe-file newpath
))
1208 (not (directory-pathname-p probed
)))
1209 "Can't create directory ~A,~
1210 ~%a file with the same name already exists."
1211 "Can't create directory ~A")
1212 :format-arguments
(list namestring
))
1214 :report
"Retry directory creation."
1215 (ensure-directories-exist
1217 :verbose verbose
:mode mode
))
1220 "Continue as if directory creation was successful."
1222 (setf created-p t
)))))
1223 (values pathspec created-p
))))
1225 (/show0
"filesys.lisp 1000")