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 a backslash to
53 ;;; cause it to be treated as a regular character.
54 (defun remove-backslashes (namestr start end)
56 "Remove any occurrences of #\\ from the string because we've already
57 checked for whatever they may have protected."
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 #\\)
74 (setf (schar result dst) char)
77 (error 'namestring-parse-error
78 :complaint "backslash in a bad place"
81 (%shrink-vector result dst)))
83 (defun maybe-make-pattern (namestr start end)
84 (declare (type simple-string namestr)
85 (type index start end))
89 (last-regular-char nil)
91 (flet ((flush-pending-regulars ()
92 (when last-regular-char
93 (pattern (if any-quotes
94 (remove-backslashes namestr
97 (subseq namestr last-regular-char index)))
99 (setf last-regular-char nil))))
103 (let ((char (schar namestr index)))
110 (unless last-regular-char
111 (setf last-regular-char index))
114 (flush-pending-regulars)
115 (pattern :single-char-wild)
118 (flush-pending-regulars)
119 (pattern :multi-char-wild)
122 (flush-pending-regulars)
124 (position #\] namestr :start index :end end)))
125 (unless close-bracket
126 (error 'namestring-parse-error
127 :complaint "#\\[ with no corresponding #\\]"
130 (pattern (cons :character-set
134 (setf index (1+ close-bracket))))
136 (unless last-regular-char
137 (setf last-regular-char index))
139 (flush-pending-regulars)))
140 (cond ((null (pattern))
142 ((null (cdr (pattern)))
143 (let ((piece (first (pattern))))
145 ((member :multi-char-wild) :wild)
146 (simple-string piece)
148 (make-pattern (pattern))))))
150 (make-pattern (pattern))))))
152 (defun unparse-physical-piece (thing)
156 (let* ((srclen (length thing))
159 (case (schar thing i)
162 (let ((result (make-string dstlen))
164 (dotimes (src srclen)
165 (let ((char (schar thing src)))
168 (setf (schar result dst) #\\)
170 (setf (schar result dst) char)
174 (with-output-to-string (s)
175 (dolist (piece (pattern-pieces thing))
178 (write-string piece s))
182 (write-string "*" s))
184 (write-string "?" s))))
189 (write-string (cdr piece) s)
190 (write-string "]" s))
192 (error "invalid pattern piece: ~S" piece))))))))))
194 (defun make-matcher (piece)
195 (cond ((eq piece :wild)
197 ((typep piece 'pattern)
199 (when (stringp other)
200 (pattern-matches piece other))))
203 (equal piece other)))))
205 (/show0 "filesys.lisp 160")
207 (defun extract-name-type-and-version (namestr start end)
208 (declare (type simple-string namestr)
209 (type index start end))
210 (let* ((last-dot (position #\. namestr :start (1+ start) :end end
214 (values (maybe-make-pattern namestr start last-dot)
215 (maybe-make-pattern namestr (1+ last-dot) end)
218 (values (maybe-make-pattern namestr start end)
222 (/show0 "filesys.lisp 200")
225 ;;;; Grabbing the kind of file when we have a namestring.
226 (defun native-file-kind (namestring)
227 (multiple-value-bind (existsp errno ino mode)
229 (sb!unix:unix-lstat namestring)
231 (sb!unix:unix-stat namestring)
232 (declare (ignore errno ino))
234 (let ((ifmt (logand mode sb!unix:s-ifmt)))
236 (#.sb!unix:s-ifreg :file)
237 (#.sb!unix:s-ifdir :directory)
239 (#.sb!unix:s-iflnk :symlink)
242 ;;;; TRUENAME, PROBE-FILE, FILE-AUTHOR, FILE-WRITE-DATE.
244 ;;; Rewritten in 12/2007 by RMK, replacing 13+ year old CMU code that
245 ;;; made a mess of things in order to support search lists (which SBCL
246 ;;; has never had). These are now all relatively straightforward
247 ;;; wrappers around stat(2) and realpath(2), with the same basic logic
248 ;;; in all cases. The wrinkles to be aware of:
250 ;;; * SBCL defines the truename of an existing, dangling or
251 ;;; self-referring symlink to be the symlink itself.
252 ;;; * The old version of PROBE-FILE merged the pathspec against
253 ;;; *DEFAULT-PATHNAME-DEFAULTS* twice, and so lost when *D-P-D*
254 ;;; was a relative pathname. Even if the case where *D-P-D* is a
255 ;;; relative pathname is problematic, there's no particular reason
256 ;;; to get that wrong, so let's try not to.
257 ;;; * Note that while stat(2) is probably atomic, getting the truename
258 ;;; for a filename involves poking all over the place, and so is
259 ;;; subject to race conditions if other programs mutate the file
260 ;;; system while we're resolving symlinks. So it's not implausible for
261 ;;; realpath(3) to fail even if stat(2) succeeded. There's nothing
262 ;;; obvious we can do about this, however.
263 ;;; * Windows' apparent analogue of realpath(3) is called
264 ;;; GetFullPathName, and it's a bit less useful than realpath(3).
265 ;;; In particular, while realpath(3) errors in case the file doesn't
266 ;;; exist, GetFullPathName seems to return a filename in all cases.
267 ;;; As realpath(3) is not atomic anyway, we only ever call it when
268 ;;; we think a file exists, so just be careful when rewriting this
271 ;;; Given a pathname designator, some quality to query for, return one
272 ;;; of a pathname, a universal time, or a string (a file-author), or
273 ;;; NIL. QUERY-FOR may be one of :TRUENAME, :EXISTENCE, :WRITE-DATE,
274 ;;; :AUTHOR. If ERRORP is false, return NIL in case the file system
275 ;;; returns an error code; otherwise, signal an error. Accepts
276 ;;; logical pathnames, too (but never returns LPNs). For internal
278 (defun query-file-system (pathspec query-for &optional (errorp t))
279 (let ((pathname (translate-logical-pathname
282 (sane-default-pathname-defaults)))))
283 (when (wild-pathname-p pathname)
284 (error 'simple-file-error
286 :format-control "~@<can't find the ~A of wild pathname ~A~
287 (physicalized from ~A).~:>"
288 :format-arguments (list query-for pathname pathspec)))
289 (flet ((fail (note-format pathname errno)
291 (simple-file-perror note-format pathname errno)
292 (return-from query-file-system nil))))
293 (let ((filename (native-namestring pathname :as-file t)))
296 ((:existence :truename)
297 (multiple-value-bind (file kind)
298 (sb!win32::native-probe-file-name filename)
299 (when (and (not file) kind)
300 (setf file filename))
301 ;; The following OR was an AND, but that breaks files like NUL,
302 ;; for which GetLongPathName succeeds yet GetFileAttributesEx
303 ;; fails to return the file kind. --DFL
306 (parse-native-namestring
308 (pathname-host pathname)
309 (sane-default-pathname-defaults)
310 :as-directory (eq :directory kind)))
311 (fail "couldn't resolve ~A" filename
312 (- (sb!win32:get-last-error))))))
314 (or (sb!win32::native-file-write-date filename)
315 (fail "couldn't query write date of ~A" filename
316 (- (sb!win32:get-last-error))))))
318 (multiple-value-bind (existsp errno ino mode nlink uid gid rdev size
320 (sb!unix:unix-stat filename)
321 (declare (ignore ino nlink gid rdev size atime))
322 (labels ((parse (filename &key (as-directory
327 (parse-native-namestring
329 (pathname-host pathname)
330 (sane-default-pathname-defaults)
331 :as-directory as-directory)))
332 (resolve-problematic-symlink (&optional realpath-failed)
333 ;; SBCL has for many years had a policy that a pathname
334 ;; that names an existing, dangling or self-referential
335 ;; symlink denotes the symlink itself. stat(2) fails
336 ;; and sets errno to ENOENT or ELOOP respectively, but
337 ;; we must distinguish cases where the symlink exists
338 ;; from ones where there's a loop in the apparent
339 ;; containing directory.
340 ;; Also handles symlinks in /proc/pid/fd/ to
341 ;; pipes or sockets on Linux
342 (multiple-value-bind (linkp ignore ino mode nlink uid gid rdev
344 (sb!unix:unix-lstat filename)
345 (declare (ignore ignore ino mode nlink gid rdev size atime))
346 (when (and (or (= errno sb!unix:enoent)
347 (= errno sb!unix:eloop)
350 (return-from query-file-system
353 ;; We do this reparse so as to return a
354 ;; normalized pathname.
355 (parse filename :as-directory nil))
357 ;; So here's a trick: since lstat succeded,
358 ;; FILENAME exists, so its directory exists and
359 ;; only the non-directory part is loopy. So
360 ;; let's resolve FILENAME's directory part with
361 ;; realpath(3), in order to get a canonical
362 ;; absolute name for the directory, and then
363 ;; return a pathname having PATHNAME's name,
364 ;; type, and version, but the rest from the
365 ;; truename of the directory. Since we turned
366 ;; PATHNAME into FILENAME "as a file", FILENAME
367 ;; does not end in a slash, and so we get the
368 ;; directory part of FILENAME by reparsing
369 ;; FILENAME and masking off its name, type, and
370 ;; version bits. But note not to call ourselves
371 ;; recursively, because we don't want to
372 ;; re-merge against *DEFAULT-PATHNAME-DEFAULTS*,
373 ;; since PATHNAME may be a relative pathname.
376 (multiple-value-bind (realpath errno)
377 (sb!unix:unix-realpath
383 :defaults (parse filename
384 :as-directory nil))))
386 (fail "couldn't resolve ~A" filename errno)))
389 (:author (sb!unix:uid-username uid))
390 (:write-date (+ unix-to-universal-time mtime))))))
391 ;; If we're still here, the file doesn't exist; error.
393 (format nil "failed to find the ~A of ~~A" query-for)
397 (:existence (parse filename))
399 ;; Note: in case the file is stat'able, POSIX
400 ;; realpath(3) gets us a canonical absolute
401 ;; filename, even if the post-merge PATHNAME
403 (parse (or (sb!unix:unix-realpath filename)
404 (resolve-problematic-symlink t))))
405 (:author (sb!unix:uid-username uid))
406 (:write-date (+ unix-to-universal-time mtime)))
407 (resolve-problematic-symlink))))))))
410 (defun probe-file (pathspec)
412 "Return the truename of PATHSPEC if the truename can be found,
413 or NIL otherwise. See TRUENAME for more information."
414 (query-file-system pathspec :truename nil))
416 (defun truename (pathspec)
418 "If PATHSPEC is a pathname that names an existing file, return
419 a pathname that denotes a canonicalized name for the file. If
420 pathspec is a stream associated with a file, return a pathname
421 that denotes a canonicalized name for the file associated with
424 An error of type FILE-ERROR is signalled if no such file exists
425 or if the file system is such that a canonicalized file name
426 cannot be determined or if the pathname is wild.
428 Under Unix, the TRUENAME of a symlink that links to itself or to
429 a file that doesn't exist is considered to be the name of the
430 broken symlink itself."
431 ;; Note that eventually this routine might be different for streams
432 ;; than for other pathname designators.
433 (if (streamp pathspec)
434 (query-file-system pathspec :truename)
435 (query-file-system pathspec :truename)))
437 (defun file-author (pathspec)
439 "Return the author of the file specified by PATHSPEC. Signal an
440 error of type FILE-ERROR if no such file exists, or if PATHSPEC
442 (query-file-system pathspec :author))
444 (defun file-write-date (pathspec)
446 "Return the write date of the file specified by PATHSPEC.
447 An error of type FILE-ERROR is signaled if no such file exists,
448 or if PATHSPEC is a wild pathname."
449 (query-file-system pathspec :write-date))
451 ;;;; miscellaneous other operations
453 (/show0 "filesys.lisp 700")
455 (defun rename-file (file new-name)
457 "Rename FILE to have the specified NEW-NAME. If FILE is a stream open to a
458 file, then the associated file is renamed."
459 (let* ((original (merge-pathnames file (sane-default-pathname-defaults)))
460 (old-truename (truename original))
461 (original-namestring (native-namestring (physicalize-pathname original)
463 (new-name (merge-pathnames new-name original))
464 (new-namestring (native-namestring (physicalize-pathname new-name)
466 (unless new-namestring
467 (error 'simple-file-error
469 :format-control "~S can't be created."
470 :format-arguments (list new-name)))
471 (multiple-value-bind (res error)
472 (sb!unix:unix-rename original-namestring new-namestring)
474 (error 'simple-file-error
476 :format-control "~@<couldn't rename ~2I~_~A ~I~_to ~2I~_~A: ~
478 :format-arguments (list original new-name (strerror error))))
480 (file-name file new-name))
481 (values new-name old-truename (truename new-name)))))
483 (defun delete-file (file)
485 "Delete the specified FILE.
487 If FILE is a stream, on Windows the stream is closed immediately. On Unix
488 plaforms the stream remains open, allowing IO to continue: the OS resources
489 associated with the deleted file remain available till the stream is closed as
490 per standard Unix unlink() behaviour."
491 (let* ((pathname (translate-logical-pathname
492 (merge-pathnames file (sane-default-pathname-defaults))))
493 (namestring (native-namestring pathname :as-file t)))
497 (multiple-value-bind (res err)
498 #!-win32 (sb!unix:unix-unlink namestring)
499 #!+win32 (or (sb!win32::native-delete-file namestring)
500 (values nil (- (sb!win32:get-last-error))))
502 (simple-file-perror "couldn't delete ~A" namestring err))))
505 (defun directorize-pathname (pathname)
506 (if (or (pathname-name pathname)
507 (pathname-type pathname))
508 (make-pathname :directory (append (pathname-directory pathname)
509 (list (file-namestring pathname)))
510 :host (pathname-host pathname)
511 :device (pathname-device pathname))
514 (defun delete-directory (pathspec &key recursive)
515 "Deletes the directory designated by PATHSPEC (a pathname designator).
516 Returns the truename of the directory deleted.
518 If RECURSIVE is false \(the default), signals an error unless the directory is
519 empty. If RECURSIVE is true, first deletes all files and subdirectories. If
520 RECURSIVE is true and the directory contains symbolic links, the links are
521 deleted, not the files and directories they point to.
523 Signals an error if PATHSPEC designates a file or a symbolic link instead of a
524 directory, or if the directory could not be deleted for any reason.
528 \(DELETE-DIRECTORY \"/tmp/foo\")
529 \(DELETE-DIRECTORY \"/tmp/foo/\")
531 delete the \"foo\" subdirectory of \"/tmp\", or signal an error if it does not
532 exist or if is a file or a symbolic link."
533 (declare (type pathname-designator pathspec))
534 (let ((physical (directorize-pathname
535 (physicalize-pathname
537 pathspec (sane-default-pathname-defaults))))))
538 (labels ((recurse-merged (dir)
540 (recurse (merge-pathnames sub dir))))
543 (delete-file (merge-pathnames file dir))))
545 (map-directory (recurse-merged dir) dir
548 :classify-symlinks nil)
549 (map-directory (delete-merged dir) dir
552 :classify-symlinks nil)
555 (let ((namestring (native-namestring dir :as-file t)))
556 (multiple-value-bind (res errno)
558 (or (sb!win32::native-delete-directory namestring)
559 (values nil (- (sb!win32:get-last-error))))
562 (not (minusp (alien-funcall
563 (extern-alien "rmdir"
564 (function int c-string))
570 "Could not delete directory ~A"
571 namestring errno))))))
574 (delete-dir physical)))))
577 (defun sbcl-homedir-pathname ()
578 (let ((sbcl-home (posix-getenv "SBCL_HOME")))
579 ;; SBCL_HOME isn't set for :EXECUTABLE T embedded cores
580 (when (and sbcl-home (not (string= sbcl-home "")))
581 (parse-native-namestring sbcl-home
582 #!-win32 sb!impl::*unix-host*
583 #!+win32 sb!impl::*win32-host*
584 *default-pathname-defaults*
587 (defun user-homedir-namestring (&optional username)
589 (sb!unix:user-homedir username)
590 (let ((env-home (posix-getenv "HOME")))
591 (if (and env-home (not (string= env-home "")))
594 (sb!unix:uid-homedir (sb!unix:unix-getuid))))))
596 ;;; (This is an ANSI Common Lisp function.)
597 (defun user-homedir-pathname (&optional host)
599 "Return the home directory of the user as a pathname. If the HOME
600 environment variable has been specified, the directory it designates
601 is returned; otherwise obtains the home directory from the operating
602 system. HOST argument is ignored by SBCL."
603 (declare (ignore host))
605 (parse-native-namestring
606 (or (user-homedir-namestring)
608 (sb!win32::get-folder-namestring sb!win32::csidl_profile))
609 #!-win32 sb!impl::*unix-host*
610 #!+win32 sb!impl::*win32-host*
611 *default-pathname-defaults*
617 (defun directory (pathspec &key (resolve-symlinks t))
619 "Return a list of PATHNAMEs, each the TRUENAME of a file that matched the
620 given pathname. Note that the interaction between this ANSI-specified
621 TRUENAMEing and the semantics of the Unix filesystem (symbolic links..) means
622 this function can sometimes return files which don't have the same directory
623 as PATHNAME. If :RESOLVE-SYMLINKS is NIL, don't resolve symbolic links in
625 (let (;; We create one entry in this hash table for each truename,
626 ;; as an asymptotically efficient way of removing duplicates
627 ;; (which can arise when e.g. multiple symlinks map to the
629 (truenames (make-hash-table :test #'equal)))
630 (labels ((record (pathname)
631 (let ((truename (if resolve-symlinks
632 ;; FIXME: Why not not TRUENAME? As reported by
633 ;; Milan Zamazal sbcl-devel 2003-10-05, using
634 ;; TRUENAME causes a race condition whereby
635 ;; removal of a file during the directory
636 ;; operation causes an error. It's not clear
637 ;; what the right thing to do is, though. --
639 (query-file-system pathname :truename nil)
640 (query-file-system pathname :existence nil))))
642 (setf (gethash (namestring truename) truenames)
644 (do-physical-pathnames (pathname)
645 (aver (not (logical-pathname-p pathname)))
646 (let* (;; KLUDGE: Since we don't canonize pathnames on construction,
647 ;; we really have to do it here to get #p"foo/." mean the same
649 (pathname (canonicalize-pathname pathname))
650 (name (pathname-name pathname))
651 (type (pathname-type pathname))
652 (match-name (make-matcher name))
653 (match-type (make-matcher type)))
654 (map-matching-directories
657 (map-matching-entries #'record
663 (do-pathnames (pathname)
664 (if (logical-pathname-p pathname)
665 (let ((host (intern-logical-host (pathname-host pathname))))
666 (dolist (x (logical-host-canon-transls host))
667 (destructuring-bind (from to) x
669 (pathname-intersections pathname from)))
670 (dolist (p intersections)
671 (do-pathnames (translate-pathname p from to)))))))
672 (do-physical-pathnames pathname))))
673 (declare (truly-dynamic-extent #'record))
674 (do-pathnames (merge-pathnames pathspec)))
676 ;; Sorting isn't required by the ANSI spec, but sorting into some
677 ;; canonical order seems good just on the grounds that the
678 ;; implementation should have repeatable behavior when possible.
679 (sort (loop for namestring being each hash-key in truenames
680 using (hash-value truename)
681 collect (cons namestring truename))
685 (defun canonicalize-pathname (pathname)
686 ;; We're really only interested in :UNSPECIFIC -> NIL, :BACK and :UP,
687 ;; and dealing with #p"foo/.." and #p"foo/."
688 (labels ((simplify (piece)
689 (unless (eq :unspecific piece)
691 (canonicalize-directory (directory)
693 (dolist (piece directory)
695 ((and pieces (member piece '(:back :up)))
696 ;; FIXME: We should really canonicalize when we construct
697 ;; pathnames. This is just wrong.
699 ((:absolute :wild-inferiors)
700 (error 'simple-file-error
701 :format-control "Invalid use of ~S after ~S."
702 :format-arguments (list piece (car pieces))
704 ((:relative :up :back)
709 ;; This case only really matters on Windows,
710 ;; because on POSIX, our call site (TRUENAME via
711 ;; QUERY-FILE-SYSTEM) only passes in pathnames from
712 ;; realpath(3), in which /./ has been removed
713 ;; already. Windows, however, depends on us to
714 ;; perform this fixup. -- DFL
717 (push piece pieces))))
719 (let ((name (simplify (pathname-name pathname)))
720 (type (simplify (pathname-type pathname)))
721 (dir (canonicalize-directory (pathname-directory pathname))))
722 (cond ((equal "." name)
724 (make-pathname :name nil :defaults pathname))
726 (make-pathname :name nil
728 :directory (butlast dir)
729 :defaults pathname))))
731 (make-pathname :name name :type type
733 :defaults pathname))))))
735 ;;; Given a native namestring, provides a WITH-HASH-TABLE-ITERATOR style
736 ;;; interface to mapping over namestrings of entries in the corresponding
738 (defmacro with-native-directory-iterator ((iterator namestring &key errorp) &body body)
739 (with-unique-names (one-iter)
741 ((iterate (,one-iter)
742 (declare (type function ,one-iter))
743 (macrolet ((,iterator ()
744 `(funcall ,',one-iter)))
747 (sb!win32::native-call-with-directory-iterator
748 #'iterate ,namestring ,errorp)
750 (call-with-native-directory-iterator #'iterate ,namestring ,errorp))))
752 (defun call-with-native-directory-iterator (function namestring errorp)
753 (declare (type (or null string) namestring)
761 (let ((ent (sb!unix:unix-readdir dp nil)))
763 (let ((name (sb!unix:unix-dirent-name ent)))
765 (cond ((equal "." name)
770 (return-from one-iter name))))))))))
773 (setf dp (sb!unix:unix-opendir namestring errorp))
775 (funcall function #'one-iter)))
777 (sb!unix:unix-closedir dp nil)))))))
779 ;;; This is our core directory access interface that we use to implement
781 (defun map-directory (function directory &key (files t) (directories t)
782 (classify-symlinks t) (errorp t))
784 "Map over entries in DIRECTORY. Keyword arguments specify which entries to
788 If true, call FUNCTION with the pathname of each file in DIRECTORY.
792 If true, call FUNCTION with a pathname for each subdirectory of DIRECTORY.
793 If :AS-FILES, the pathname used is a pathname designating the subdirectory
794 as a file in DIRECTORY. Otherwise the pathname used is a directory
795 pathname. Defaults to T.
798 If true, the decision to call FUNCTION with the pathname of a symbolic link
799 depends on the resolution of the link: if it points to a directory, it is
800 considered a directory entry, otherwise a file entry. If false, all
801 symbolic links are considered file entries. In both cases the pathname used
802 for the symbolic link is not fully resolved, but names it as an immediate
803 child of DIRECTORY. Defaults to T.
806 If true, signal an error if DIRECTORY does not exist, cannot be read, etc.
809 Experimental: interface subject to change."
810 (declare (pathname-designator directory))
811 (let* ((fun (%coerce-callable-to-fun function))
812 (as-files (eq :as-files directories))
813 (physical (physicalize-pathname directory))
814 (realname (query-file-system physical :existence nil))
815 (canonical (if realname
816 (parse-native-namestring realname
817 (pathname-host physical)
818 (sane-default-pathname-defaults)
820 (return-from map-directory nil)))
821 (dirname (native-namestring canonical)))
822 (flet ((map-it (name dirp)
824 (merge-pathnames (parse-native-namestring
826 :as-directory (and dirp (not as-files)))
828 (with-native-directory-iterator (next dirname :errorp errorp)
830 ;; provision for FindFirstFileExW-based iterator that should be used
831 ;; on Windows: file kind is known instantly there, so we'll have it
832 ;; returned by (next) soon.
833 (multiple-value-bind (name kind) (next)
834 (unless (or name kind) (return))
836 (setf kind (native-file-kind
837 (concatenate 'string dirname name))))
844 (if classify-symlinks
845 (let* ((tmpname (merge-pathnames
846 (parse-native-namestring
847 name nil physical :as-directory nil)
849 (truename (query-file-system tmpname :truename nil)))
850 (if (or (not truename)
851 (or (pathname-name truename) (pathname-type truename)))
853 (funcall fun tmpname))
859 ;; Anything else parses as a file.
861 (map-it name nil)))))))))))
863 ;;; Part of DIRECTORY: implements matching the directory spec. Calls FUNCTION
864 ;;; with all DIRECTORIES that match the directory portion of PATHSPEC.
865 (defun map-matching-directories (function pathspec)
866 (let* ((dir (pathname-directory pathspec))
867 (length (length dir))
868 (wild (position-if (lambda (elt)
869 (or (eq :wild elt) (typep elt 'pattern)))
871 (wild-inferiors (position :wild-inferiors dir))
872 (end (cond ((and wild wild-inferiors)
873 (min wild wild-inferiors))
875 (or wild wild-inferiors length))))
876 (rest (subseq dir end))
877 (starting-point (make-pathname :directory (subseq dir 0 end)
878 :device (pathname-device pathspec)
879 :host (pathname-host pathspec)
883 (cond (wild-inferiors
884 (map-wild-inferiors function rest starting-point))
886 (map-wild function rest starting-point))
888 ;; Nothing wild -- the directory matches itself.
889 (funcall function starting-point))))
892 (defun last-directory-piece (pathname)
893 (car (last (pathname-directory pathname))))
895 ;;; Part of DIRECTORY: implements iterating over a :WILD or pattern component
896 ;;; in the directory spec.
897 (defun map-wild (function more directory)
898 (let ((this (pop more))
900 (flet ((cont (subdirectory)
903 (funcall function subdirectory))
904 ((or (eq :wild next) (typep next 'pattern))
905 (map-wild function more subdirectory))
906 ((eq :wild-inferiors next)
907 (map-wild-inferiors function more subdirectory))
909 (let ((this (pathname-directory subdirectory)))
910 (map-matching-directories
912 (make-pathname :directory (append this more)
913 :defaults subdirectory)))))))
918 (when (pattern-matches this (last-directory-piece sub))
919 (funcall #'cont sub))))
925 ;;; Part of DIRECTORY: implements iterating over a :WILD-INFERIORS component
926 ;;; in the directory spec.
927 (defun map-wild-inferiors (function more directory)
928 (loop while (member (car more) '(:wild :wild-inferiors))
930 (let ((next (car more))
933 (funcall function directory))
937 (funcall function pathname)
938 (map-wild-inferiors function more pathname)))
941 (let ((this (pathname-directory pathname)))
942 (when (equal next (car (last this)))
943 (map-matching-directories
945 (make-pathname :directory (append this rest)
946 :defaults pathname)))
947 (map-wild-inferiors function more pathname)))))
953 ;;; Part of DIRECTORY: implements iterating over entries in a directory, and
955 (defun map-matching-entries (function directory match-name match-type)
958 (when (and (funcall match-name (pathname-name file))
959 (funcall match-type (pathname-type file)))
960 (funcall function file)))
963 :directories :as-files
966 ;;; NOTE: There is a fair amount of hair below that is probably not
967 ;;; strictly necessary.
969 ;;; The issue is the following: what does (DIRECTORY "SYS:*;") mean?
970 ;;; Until 2004-01, SBCL's behaviour was unquestionably wrong, as it
971 ;;; did not translate the logical pathname at all, but instead treated
972 ;;; it as a physical one. Other Lisps seem to to treat this call as
973 ;;; equivalent to (DIRECTORY (TRANSLATE-LOGICAL-PATHNAME "SYS:*;")),
974 ;;; which is fine as far as it goes, but not very interesting, and
975 ;;; arguably counterintuitive. (PATHNAME-MATCH-P "SYS:SRC;" "SYS:*;")
976 ;;; is true, so why should "SYS:SRC;" not show up in the call to
977 ;;; DIRECTORY? (assuming the physical pathname corresponding to it
978 ;;; exists, of course).
980 ;;; So, the interpretation that I am pushing is for all pathnames
981 ;;; matching the input pathname to be queried. This means that we
982 ;;; need to compute the intersection of the input pathname and the
983 ;;; logical host FROM translations, and then translate the resulting
984 ;;; pathname using the host to the TO translation; this treatment is
985 ;;; recursively invoked until we get a physical pathname, whereupon
986 ;;; our physical DIRECTORY implementation takes over.
988 ;;; FIXME: this is an incomplete implementation. It only works when
989 ;;; both are logical pathnames (which is OK, because that's the only
990 ;;; case when we call it), but there are other pitfalls as well: see
991 ;;; the DIRECTORY-HELPER below for some, but others include a lack of
992 ;;; pattern handling.
994 ;;; The above was written by CSR, I (RMK) believe. The argument that
995 ;;; motivates the interpretation is faulty, however: PATHNAME-MATCH-P
996 ;;; returns true for (PATHNAME-MATCH-P #P"/tmp/*/" #P"/tmp/../"), but
997 ;;; the latter pathname is not in the result of DIRECTORY on the
998 ;;; former. Indeed, if DIRECTORY were constrained to return the
999 ;;; truename for every pathname for which PATHNAME-MATCH-P returned
1000 ;;; true and which denoted a filename that named an existing file,
1001 ;;; (DIRECTORY #P"/tmp/**/") would be required to list every file on a
1002 ;;; Unix system, since any file can be named as though it were "below"
1003 ;;; /tmp, given the dotdot entries. So I think the strongest
1004 ;;; "consistency" we can define between PATHNAME-MATCH-P and DIRECTORY
1005 ;;; is that PATHNAME-MATCH-P returns true of everything DIRECTORY
1006 ;;; returns, but not vice versa.
1008 ;;; In any case, even if the motivation were sound, DIRECTORY on a
1009 ;;; wild logical pathname has no portable semantics. I see nothing in
1010 ;;; ANSI that requires implementations to support wild physical
1011 ;;; pathnames, and so there need not be any translation of a wild
1012 ;;; logical pathname to a phyiscal pathname. So a program that calls
1013 ;;; DIRECTORY on a wild logical pathname is doing something
1014 ;;; non-portable at best. And if the only sensible semantics for
1015 ;;; DIRECTORY on a wild logical pathname is something like the
1016 ;;; following, it would be just as well if it signaled an error, since
1017 ;;; a program can't possibly rely on the result of an intersection of
1018 ;;; user-defined translations with a file system probe. (Potentially
1019 ;;; useful kinds of "pathname" that might not support wildcards could
1020 ;;; include pathname hosts that model unqueryable namespaces like HTTP
1021 ;;; URIs, or that model namespaces that it's not convenient to
1022 ;;; investigate, such as the namespace of TCP ports that some network
1023 ;;; host listens on. I happen to think it a bad idea to try to
1024 ;;; shoehorn such namespaces into a pathnames system, but people
1025 ;;; sometimes claim to want pathnames for these things.) -- RMK
1028 (defun pathname-intersections (one two)
1029 (aver (logical-pathname-p one))
1030 (aver (logical-pathname-p two))
1032 ((intersect-version (one two)
1033 (aver (typep one '(or null (member :newest :wild :unspecific)
1035 (aver (typep two '(or null (member :newest :wild :unspecific)
1038 ((eq one :wild) two)
1039 ((eq two :wild) one)
1040 ((or (null one) (eq one :unspecific)) two)
1041 ((or (null two) (eq two :unspecific)) one)
1044 (intersect-name/type (one two)
1045 (aver (typep one '(or null (member :wild :unspecific) string)))
1046 (aver (typep two '(or null (member :wild :unspecific) string)))
1048 ((eq one :wild) two)
1049 ((eq two :wild) one)
1050 ((or (null one) (eq one :unspecific)) two)
1051 ((or (null two) (eq two :unspecific)) one)
1052 ((string= one two) one)
1053 (t (return-from pathname-intersections nil))))
1054 (intersect-directory (one two)
1055 (aver (typep one '(or null (member :wild :unspecific) list)))
1056 (aver (typep two '(or null (member :wild :unspecific) list)))
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)
1062 (t (aver (eq (car one) (car two)))
1064 (lambda (x) (cons (car one) x))
1065 (intersect-directory-helper (cdr one) (cdr two)))))))
1066 (let ((version (intersect-version
1067 (pathname-version one) (pathname-version two)))
1068 (name (intersect-name/type
1069 (pathname-name one) (pathname-name two)))
1070 (type (intersect-name/type
1071 (pathname-type one) (pathname-type two)))
1072 (host (pathname-host one)))
1074 (make-pathname :host host :name name :type type
1075 :version version :directory d))
1076 (intersect-directory
1077 (pathname-directory one) (pathname-directory two))))))
1079 ;;; FIXME: written as its own function because I (CSR) don't
1080 ;;; understand it, so helping both debuggability and modularity. In
1081 ;;; case anyone is motivated to rewrite it, it returns a list of
1082 ;;; sublists representing the intersection of the two input directory
1083 ;;; paths (excluding the initial :ABSOLUTE or :RELATIVE).
1085 ;;; FIXME: Does not work with :UP or :BACK
1086 ;;; FIXME: Does not work with patterns
1088 ;;; FIXME: PFD suggests replacing this implementation with a DFA
1089 ;;; conversion of a NDFA. Find out (a) what this means and (b) if it
1090 ;;; turns out to be worth it.
1091 (defun intersect-directory-helper (one two)
1092 (flet ((simple-intersection (cone ctwo)
1094 ((eq cone :wild) ctwo)
1095 ((eq ctwo :wild) cone)
1096 (t (aver (typep cone 'string))
1097 (aver (typep ctwo 'string))
1098 (if (string= cone ctwo) cone nil)))))
1100 ((loop-possible-wild-inferiors-matches
1101 (lower-bound bounding-sequence order)
1102 (let ((index (gensym)) (g2 (gensym)) (g3 (gensym)) (l (gensym)))
1103 `(let ((,l (length ,bounding-sequence)))
1104 (loop for ,index from ,lower-bound to ,l
1105 append (mapcar (lambda (,g2)
1107 (butlast ,bounding-sequence (- ,l ,index))
1112 (if (eq (car (nthcdr ,index ,bounding-sequence))
1116 (intersect-directory-helper
1118 `((nthcdr ,index one) (cdr two))
1119 `((cdr one) (nthcdr ,index two)))))))))))
1121 ((and (eq (car one) :wild-inferiors)
1122 (eq (car two) :wild-inferiors))
1124 (append (mapcar (lambda (x) (cons :wild-inferiors x))
1125 (intersect-directory-helper (cdr one) (cdr two)))
1126 (loop-possible-wild-inferiors-matches 2 one t)
1127 (loop-possible-wild-inferiors-matches 2 two nil))
1129 ((eq (car one) :wild-inferiors)
1130 (delete-duplicates (loop-possible-wild-inferiors-matches 0 two nil)
1132 ((eq (car two) :wild-inferiors)
1133 (delete-duplicates (loop-possible-wild-inferiors-matches 0 one t)
1135 ((and (null one) (null two)) (list nil))
1138 (t (and (simple-intersection (car one) (car two))
1139 (mapcar (lambda (x) (cons (simple-intersection
1140 (car one) (car two)) x))
1141 (intersect-directory-helper (cdr one) (cdr two)))))))))
1144 (defun directory-pathname-p (pathname)
1145 (and (pathnamep pathname)
1146 (null (pathname-name pathname))
1147 (null (pathname-type pathname))))
1149 (defun ensure-directories-exist (pathspec &key verbose (mode #o777))
1151 "Test whether the directories containing the specified file
1152 actually exist, and attempt to create them if they do not.
1153 The MODE argument is a CMUCL/SBCL-specific extension to control
1154 the Unix permission bits."
1155 (let ((pathname (physicalize-pathname (merge-pathnames (pathname pathspec))))
1157 (when (wild-pathname-p pathname)
1158 (error 'simple-file-error
1159 :format-control "bad place for a wild pathname"
1160 :pathname pathspec))
1161 (let* ((dir (pathname-directory pathname))
1162 (*default-pathname-defaults*
1163 (make-pathname :directory dir :device (pathname-device pathname)))
1164 (dev (pathname-device pathname)))
1165 (loop for i from (case dev (:unc 3) (otherwise 2))
1168 (let* ((newpath (make-pathname
1169 :host (pathname-host pathname)
1171 :directory (subseq dir 0 i)))
1172 (probed (probe-file newpath)))
1173 (unless (directory-pathname-p probed)
1174 (let ((namestring (coerce (native-namestring newpath)
1177 (format *standard-output*
1178 "~&creating directory: ~A~%"
1180 (sb!unix:unix-mkdir namestring mode)
1181 (unless (directory-pathname-p (probe-file newpath))
1188 (not (directory-pathname-p probed)))
1189 "Can't create directory ~A,~
1190 ~%a file with the same name already exists."
1191 "Can't create directory ~A")
1192 :format-arguments (list namestring))
1194 :report "Retry directory creation."
1195 (ensure-directories-exist
1197 :verbose verbose :mode mode))
1200 "Continue as if directory creation was successful."
1202 (setf created-p t)))))
1203 (values pathspec created-p))))
1205 (/show0 "filesys.lisp 1000")