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)))
294 (multiple-value-bind (existsp errno ino mode nlink uid gid rdev size
296 (sb!unix:unix-stat filename)
297 (declare (ignore ino nlink gid rdev size atime
300 ;; On win32, stat regards UNC pathnames and device names as
301 ;; nonexisting, so we check once more with the native API.
304 (let ((handle (sb!win32:create-file
306 sb!win32:file-open-existing
312 (sb!win32:get-file-attributes filename))
314 (progn (sb!win32:close-handle handle) t)))))
317 (:existence (nth-value
319 (parse-native-namestring
321 (pathname-host pathname)
322 (sane-default-pathname-defaults)
323 :as-directory (eql (logand mode sb!unix:s-ifmt)
325 (:truename (nth-value
327 (parse-native-namestring
328 ;; Note: in case the file is stat'able, POSIX
329 ;; realpath(3) gets us a canonical absolute
330 ;; filename, even if the post-merge PATHNAME
331 ;; is not absolute...
332 (multiple-value-bind (realpath errno)
333 (sb!unix:unix-realpath filename)
336 (fail "couldn't resolve ~A" filename errno)))
337 (pathname-host pathname)
338 (sane-default-pathname-defaults)
339 ;; ... but without any trailing slash.
340 :as-directory (eql (logand mode sb!unix:s-ifmt)
344 (sb!unix:uid-username uid))
345 (:write-date (+ unix-to-universal-time mtime)))
347 ;; SBCL has for many years had a policy that a pathname
348 ;; that names an existing, dangling or self-referential
349 ;; symlink denotes the symlink itself. stat(2) fails
350 ;; and sets errno to ENOENT or ELOOP respectively, but
351 ;; we must distinguish cases where the symlink exists
352 ;; from ones where there's a loop in the apparent
353 ;; containing directory.
355 (multiple-value-bind (linkp ignore ino mode nlink uid gid rdev
357 (sb!unix:unix-lstat filename)
358 (declare (ignore ignore ino mode nlink gid rdev size atime))
359 (when (and (or (= errno sb!unix:enoent)
360 (= errno sb!unix:eloop))
362 (return-from query-file-system
365 ;; We do this reparse so as to return a
366 ;; normalized pathname.
367 (parse-native-namestring
368 filename (pathname-host pathname)))
370 ;; So here's a trick: since lstat succeded,
371 ;; FILENAME exists, so its directory exists and
372 ;; only the non-directory part is loopy. So
373 ;; let's resolve FILENAME's directory part with
374 ;; realpath(3), in order to get a canonical
375 ;; absolute name for the directory, and then
376 ;; return a pathname having PATHNAME's name,
377 ;; type, and version, but the rest from the
378 ;; truename of the directory. Since we turned
379 ;; PATHNAME into FILENAME "as a file", FILENAME
380 ;; does not end in a slash, and so we get the
381 ;; directory part of FILENAME by reparsing
382 ;; FILENAME and masking off its name, type, and
383 ;; version bits. But note not to call ourselves
384 ;; recursively, because we don't want to
385 ;; re-merge against *DEFAULT-PATHNAME-DEFAULTS*,
386 ;; since PATHNAME may be a relative pathname.
390 (parse-native-namestring
391 (multiple-value-bind (realpath errno)
392 (sb!unix:unix-realpath
398 :defaults (parse-native-namestring
400 (pathname-host pathname)
401 (sane-default-pathname-defaults)))))
404 (fail "couldn't resolve ~A" filename errno)))
405 (pathname-host pathname)
406 (sane-default-pathname-defaults)
409 (:author (sb!unix:uid-username uid))
410 (:write-date (+ unix-to-universal-time mtime))))))
411 ;; If we're still here, the file doesn't exist; error.
413 (format nil "failed to find the ~A of ~~A" query-for)
414 pathspec errno))))))))
417 (defun probe-file (pathspec)
419 "Return the truename of PATHSPEC if the truename can be found,
420 or NIL otherwise. See TRUENAME for more information."
421 (query-file-system pathspec :truename nil))
423 (defun truename (pathspec)
425 "If PATHSPEC is a pathname that names an existing file, return
426 a pathname that denotes a canonicalized name for the file. If
427 pathspec is a stream associated with a file, return a pathname
428 that denotes a canonicalized name for the file associated with
431 An error of type FILE-ERROR is signalled if no such file exists
432 or if the file system is such that a canonicalized file name
433 cannot be determined or if the pathname is wild.
435 Under Unix, the TRUENAME of a symlink that links to itself or to
436 a file that doesn't exist is considered to be the name of the
437 broken symlink itself."
438 ;; Note that eventually this routine might be different for streams
439 ;; than for other pathname designators.
440 (if (streamp pathspec)
441 (query-file-system pathspec :truename)
442 (query-file-system pathspec :truename)))
444 (defun file-author (pathspec)
446 "Return the author of the file specified by PATHSPEC. Signal an
447 error of type FILE-ERROR if no such file exists, or if PATHSPEC
449 (query-file-system pathspec :author))
451 (defun file-write-date (pathspec)
453 "Return the write date of the file specified by PATHSPEC.
454 An error of type FILE-ERROR is signaled if no such file exists,
455 or if PATHSPEC is a wild pathname."
456 (query-file-system pathspec :write-date))
458 ;;;; miscellaneous other operations
460 (/show0 "filesys.lisp 700")
462 (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 (truename file))
467 (original-namestring (native-namestring original :as-file t))
468 (new-name (merge-pathnames new-name original))
469 (new-namestring (native-namestring (physicalize-pathname new-name)
471 (unless new-namestring
472 (error 'simple-file-error
474 :format-control "~S can't be created."
475 :format-arguments (list new-name)))
476 (multiple-value-bind (res error)
477 (sb!unix:unix-rename original-namestring new-namestring)
479 (error 'simple-file-error
481 :format-control "~@<couldn't rename ~2I~_~A ~I~_to ~2I~_~A: ~
483 :format-arguments (list original new-name (strerror error))))
485 (file-name file new-name))
486 (values new-name original (truename new-name)))))
488 (defun delete-file (file)
490 "Delete the specified FILE.
492 If FILE is a stream, on Windows the stream is closed immediately. On Unix
493 plaforms the stream remains open, allowing IO to continue: the OS resources
494 associated with the deleted file remain available till the stream is closed as
495 per standard Unix unlink() behaviour."
496 (let* ((pathname (translate-logical-pathname
497 (merge-pathnames file (sane-default-pathname-defaults))))
498 (namestring (native-namestring pathname :as-file t)))
502 (multiple-value-bind (res err) (sb!unix:unix-unlink namestring)
504 (simple-file-perror "couldn't delete ~A" namestring err))))
507 (defun delete-directory (pathspec &key recursive)
508 "Deletes the directory designated by PATHSPEC (a pathname designator).
509 Returns the truename of the directory deleted.
511 If RECURSIVE is false \(the default), signals an error unless the directory is
512 empty. If RECURSIVE is true, first deletes all files and subdirectories. If
513 RECURSIVE is true and the directory contains symbolic links, the links are
514 deleted, not the files and directories they point to.
516 Signals an error if PATHSPEC designates a file instead of a directory, or if
517 the directory could not be deleted for any reason.
519 \(DELETE-DIRECTORY \"/tmp/foo\") and \(DELETE-DIRECTORY \"/tmp/foo/\") both
520 delete the \"foo\" subdirectory of \"/tmp\", or signal an error if it does not
522 (declare (type pathname-designator pathspec))
523 (with-pathname (pathname pathspec)
524 (let ((truename (truename (translate-logical-pathname pathname))))
525 (labels ((recurse (dir)
526 (map-directory #'recurse dir
529 :classify-symlinks nil)
530 (map-directory #'delete-file dir
533 :classify-symlinks nil)
536 (let* ((namestring (native-namestring dir :as-file t))
537 (res (alien-funcall (extern-alien #!-win32 "rmdir"
539 (function int c-string))
542 (simple-file-perror "Could not delete directory ~A:~% ~A"
543 namestring (get-errno))
547 (delete-dir truename))))))
549 (defun sbcl-homedir-pathname ()
550 (let ((sbcl-home (posix-getenv "SBCL_HOME")))
551 ;; SBCL_HOME isn't set for :EXECUTABLE T embedded cores
552 (when (and sbcl-home (not (string= sbcl-home "")))
553 (parse-native-namestring sbcl-home
554 #!-win32 sb!impl::*unix-host*
555 #!+win32 sb!impl::*win32-host*
556 *default-pathname-defaults*
559 (defun user-homedir-namestring (&optional username)
561 (sb!unix:user-homedir username)
562 (let ((env-home (posix-getenv "HOME")))
563 (if (and env-home (not (string= env-home "")))
566 (sb!unix:uid-homedir (sb!unix:unix-getuid))))))
568 ;;; (This is an ANSI Common Lisp function.)
569 (defun user-homedir-pathname (&optional host)
571 "Return the home directory of the user as a pathname. If the HOME
572 environment variable has been specified, the directory it designates
573 is returned; otherwise obtains the home directory from the operating
574 system. HOST argument is ignored by SBCL."
575 (declare (ignore host))
577 (parse-native-namestring
578 (or (user-homedir-namestring)
580 (sb!win32::get-folder-namestring sb!win32::csidl_profile))
581 #!-win32 sb!impl::*unix-host*
582 #!+win32 sb!impl::*win32-host*
583 *default-pathname-defaults*
589 (defun directory (pathspec &key (resolve-symlinks t))
591 "Return a list of PATHNAMEs, each the TRUENAME of a file that matched the
592 given pathname. Note that the interaction between this ANSI-specified
593 TRUENAMEing and the semantics of the Unix filesystem (symbolic links..) means
594 this function can sometimes return files which don't have the same directory
595 as PATHNAME. If :RESOLVE-SYMLINKS is NIL, don't resolve symbolic links in
597 (let (;; We create one entry in this hash table for each truename,
598 ;; as an asymptotically efficient way of removing duplicates
599 ;; (which can arise when e.g. multiple symlinks map to the
601 (truenames (make-hash-table :test #'equal)))
602 (labels ((record (pathname)
603 (let ((truename (if resolve-symlinks
604 ;; FIXME: Why not not TRUENAME? As reported by
605 ;; Milan Zamazal sbcl-devel 2003-10-05, using
606 ;; TRUENAME causes a race condition whereby
607 ;; removal of a file during the directory
608 ;; operation causes an error. It's not clear
609 ;; what the right thing to do is, though. --
611 (query-file-system pathname :truename nil)
612 (query-file-system pathname :existence nil))))
614 (setf (gethash (namestring truename) truenames)
616 (do-physical-pathnames (pathname)
617 (aver (not (logical-pathname-p pathname)))
618 (let* (;; KLUDGE: Since we don't canonize pathnames on construction,
619 ;; we really have to do it here to get #p"foo/." mean the same
621 (pathname (canonicalize-pathname pathname))
622 (name (pathname-name pathname))
623 (type (pathname-type pathname))
624 (match-name (make-matcher name))
625 (match-type (make-matcher type)))
626 (map-matching-directories
629 (map-matching-entries #'record
635 (do-pathnames (pathname)
636 (if (logical-pathname-p pathname)
637 (let ((host (intern-logical-host (pathname-host pathname))))
638 (dolist (x (logical-host-canon-transls host))
639 (destructuring-bind (from to) x
641 (pathname-intersections pathname from)))
642 (dolist (p intersections)
643 (do-pathnames (translate-pathname p from to)))))))
644 (do-physical-pathnames pathname))))
645 (declare (truly-dynamic-extent #'record))
646 (do-pathnames (merge-pathnames pathspec)))
648 ;; Sorting isn't required by the ANSI spec, but sorting into some
649 ;; canonical order seems good just on the grounds that the
650 ;; implementation should have repeatable behavior when possible.
651 (sort (loop for namestring being each hash-key in truenames
652 using (hash-value truename)
653 collect (cons namestring truename))
657 (defun canonicalize-pathname (pathname)
658 ;; We're really only interested in :UNSPECIFIC -> NIL, :BACK and :UP,
659 ;; and dealing with #p"foo/.." and #p"foo/."
660 (labels ((simplify (piece)
661 (unless (eq :unspecific piece)
663 (canonicalize-directory (directory)
665 (dolist (piece directory)
666 (if (and pieces (member piece '(:back :up)))
667 ;; FIXME: We should really canonicalize when we construct
668 ;; pathnames. This is just wrong.
670 ((:absolute :wild-inferiors)
671 (error 'simple-file-error
672 :format-control "Invalid use of ~S after ~S."
673 :format-arguments (list piece (car pieces))
675 ((:relative :up :back)
679 (push piece pieces)))
681 (let ((name (simplify (pathname-name pathname)))
682 (type (simplify (pathname-type pathname)))
683 (dir (canonicalize-directory (pathname-directory pathname))))
684 (cond ((equal "." name)
686 (make-pathname :name nil :defaults pathname))
688 (make-pathname :name nil
690 :directory (butlast dir)
691 :defaults pathname))))
693 (make-pathname :name name :type type
695 :defaults pathname))))))
697 ;;; Given a native namestring, provides a WITH-HASH-TABLE-ITERATOR style
698 ;;; interface to mapping over namestrings of entries in the corresponding
700 (defmacro with-native-directory-iterator ((iterator namestring &key errorp) &body body)
701 (with-unique-names (one-iter)
703 ((iterate (,one-iter)
704 (declare (type function ,one-iter))
705 (macrolet ((,iterator ()
706 `(funcall ,',one-iter)))
708 (call-with-native-directory-iterator #'iterate ,namestring ,errorp))))
710 (defun call-with-native-directory-iterator (function namestring errorp)
711 (declare (type (or null string) namestring)
719 (let ((ent (sb!unix:unix-readdir dp nil)))
721 (let ((name (sb!unix:unix-dirent-name ent)))
723 (cond ((equal "." name)
728 (return-from one-iter name))))))))))
731 (setf dp (sb!unix:unix-opendir namestring errorp))
733 (funcall function #'one-iter)))
735 (sb!unix:unix-closedir dp nil)))))))
737 ;;; This is our core directory access interface that we use to implement
739 (defun map-directory (function directory &key (files t) (directories t)
740 (classify-symlinks t) (errorp t))
742 "Map over entries in DIRECTORY. Keyword arguments specify which entries to
746 If true, call FUNCTION with the pathname of each file in DIRECTORY.
750 If true, call FUNCTION with a pathname for each subdirectory of DIRECTORY.
751 If :AS-FILES, the pathname used is a pathname designating the subdirectory
752 as a file in DIRECTORY. Otherwise the pathname used is a directory
753 pathname. Defaults to T.
756 If true, the decision to call FUNCTION with the pathname of a symbolic link
757 depends on the resolution of the link: if it points to a directory, it is
758 considered a directory entry, otherwise a file entry. If false, all
759 symbolic links are considered file entries. In both cases the pathname used
760 for the symbolic link is not fully resolved, but names it as an immediate
761 child of DIRECTORY. Defaults to T.
764 If true, signal an error if DIRECTORY does not exist, cannot be read, etc.
767 Experimental: interface subject to change."
768 (declare (pathname-designator directory))
769 (let* ((fun (%coerce-callable-to-fun function))
770 (as-files (eq :as-files directories))
771 (physical (physicalize-pathname directory))
772 ;; Not QUERY-FILE-SYSTEM :EXISTENCE, since it doesn't work on Windows
774 (realname (sb!unix:unix-realpath (native-namestring physical :as-file t)))
775 (canonical (if realname
776 (parse-native-namestring realname
777 (pathname-host physical)
778 (sane-default-pathname-defaults)
780 (return-from map-directory nil)))
781 (dirname (native-namestring canonical)))
782 (flet ((map-it (name dirp)
784 (merge-pathnames (parse-native-namestring
786 :as-directory (and dirp (not as-files)))
788 (with-native-directory-iterator (next dirname :errorp errorp)
789 (loop for name = (next)
791 do (let* ((full (concatenate 'string dirname name))
792 (kind (native-file-kind full)))
799 (if classify-symlinks
800 (let* ((tmpname (merge-pathnames
801 (parse-native-namestring
802 name nil physical :as-directory nil)
804 (truename (query-file-system tmpname :truename nil)))
805 (if (or (not truename)
806 (or (pathname-name truename) (pathname-type truename)))
808 (funcall fun tmpname))
814 ;; Anything else parses as a file.
816 (map-it name nil)))))))))))
818 ;;; Part of DIRECTORY: implements matching the directory spec. Calls FUNCTION
819 ;;; with all DIRECTORIES that match the directory portion of PATHSPEC.
820 (defun map-matching-directories (function pathspec)
821 (let* ((dir (pathname-directory pathspec))
822 (length (length dir))
823 (wild (position-if (lambda (elt)
824 (or (eq :wild elt) (typep elt 'pattern)))
826 (wild-inferiors (position :wild-inferiors dir))
827 (end (cond ((and wild wild-inferiors)
828 (min wild wild-inferiors))
830 (or wild wild-inferiors length))))
831 (rest (subseq dir end))
832 (starting-point (make-pathname :directory (subseq dir 0 end)
833 :device (pathname-device pathspec)
834 :host (pathname-host pathspec)
838 (cond (wild-inferiors
839 (map-wild-inferiors function rest starting-point))
841 (map-wild function rest starting-point))
843 ;; Nothing wild -- the directory matches itself.
844 (funcall function starting-point))))
847 (defun last-directory-piece (pathname)
848 (car (last (pathname-directory pathname))))
850 ;;; Part of DIRECTORY: implements iterating over a :WILD or pattern component
851 ;;; in the directory spec.
852 (defun map-wild (function more directory)
853 (let ((this (pop more))
855 (flet ((cont (subdirectory)
858 (funcall function subdirectory))
859 ((or (eq :wild next) (typep next 'pattern))
860 (map-wild function more subdirectory))
861 ((eq :wild-inferiors next)
862 (map-wild-inferiors function more subdirectory))
864 (let ((this (pathname-directory subdirectory)))
865 (map-matching-directories
867 (make-pathname :directory (append this more)
868 :defaults subdirectory)))))))
873 (when (pattern-matches this (last-directory-piece sub))
874 (funcall #'cont sub))))
880 ;;; Part of DIRECTORY: implements iterating over a :WILD-INFERIORS component
881 ;;; in the directory spec.
882 (defun map-wild-inferiors (function more directory)
883 (loop while (member (car more) '(:wild :wild-inferiors))
885 (let ((next (car more))
888 (funcall function directory))
892 (funcall function pathname)
893 (map-wild-inferiors function more pathname)))
896 (let ((this (pathname-directory pathname)))
897 (when (equal next (car (last this)))
898 (map-matching-directories
900 (make-pathname :directory (append this rest)
901 :defaults pathname)))
902 (map-wild-inferiors function more pathname)))))
908 ;;; Part of DIRECTORY: implements iterating over entries in a directory, and
910 (defun map-matching-entries (function directory match-name match-type)
913 (when (and (funcall match-name (pathname-name file))
914 (funcall match-type (pathname-type file)))
915 (funcall function file)))
918 :directories :as-files
921 ;;; NOTE: There is a fair amount of hair below that is probably not
922 ;;; strictly necessary.
924 ;;; The issue is the following: what does (DIRECTORY "SYS:*;") mean?
925 ;;; Until 2004-01, SBCL's behaviour was unquestionably wrong, as it
926 ;;; did not translate the logical pathname at all, but instead treated
927 ;;; it as a physical one. Other Lisps seem to to treat this call as
928 ;;; equivalent to (DIRECTORY (TRANSLATE-LOGICAL-PATHNAME "SYS:*;")),
929 ;;; which is fine as far as it goes, but not very interesting, and
930 ;;; arguably counterintuitive. (PATHNAME-MATCH-P "SYS:SRC;" "SYS:*;")
931 ;;; is true, so why should "SYS:SRC;" not show up in the call to
932 ;;; DIRECTORY? (assuming the physical pathname corresponding to it
933 ;;; exists, of course).
935 ;;; So, the interpretation that I am pushing is for all pathnames
936 ;;; matching the input pathname to be queried. This means that we
937 ;;; need to compute the intersection of the input pathname and the
938 ;;; logical host FROM translations, and then translate the resulting
939 ;;; pathname using the host to the TO translation; this treatment is
940 ;;; recursively invoked until we get a physical pathname, whereupon
941 ;;; our physical DIRECTORY implementation takes over.
943 ;;; FIXME: this is an incomplete implementation. It only works when
944 ;;; both are logical pathnames (which is OK, because that's the only
945 ;;; case when we call it), but there are other pitfalls as well: see
946 ;;; the DIRECTORY-HELPER below for some, but others include a lack of
947 ;;; pattern handling.
949 ;;; The above was written by CSR, I (RMK) believe. The argument that
950 ;;; motivates the interpretation is faulty, however: PATHNAME-MATCH-P
951 ;;; returns true for (PATHNAME-MATCH-P #P"/tmp/*/" #P"/tmp/../"), but
952 ;;; the latter pathname is not in the result of DIRECTORY on the
953 ;;; former. Indeed, if DIRECTORY were constrained to return the
954 ;;; truename for every pathname for which PATHNAME-MATCH-P returned
955 ;;; true and which denoted a filename that named an existing file,
956 ;;; (DIRECTORY #P"/tmp/**/") would be required to list every file on a
957 ;;; Unix system, since any file can be named as though it were "below"
958 ;;; /tmp, given the dotdot entries. So I think the strongest
959 ;;; "consistency" we can define between PATHNAME-MATCH-P and DIRECTORY
960 ;;; is that PATHNAME-MATCH-P returns true of everything DIRECTORY
961 ;;; returns, but not vice versa.
963 ;;; In any case, even if the motivation were sound, DIRECTORY on a
964 ;;; wild logical pathname has no portable semantics. I see nothing in
965 ;;; ANSI that requires implementations to support wild physical
966 ;;; pathnames, and so there need not be any translation of a wild
967 ;;; logical pathname to a phyiscal pathname. So a program that calls
968 ;;; DIRECTORY on a wild logical pathname is doing something
969 ;;; non-portable at best. And if the only sensible semantics for
970 ;;; DIRECTORY on a wild logical pathname is something like the
971 ;;; following, it would be just as well if it signaled an error, since
972 ;;; a program can't possibly rely on the result of an intersection of
973 ;;; user-defined translations with a file system probe. (Potentially
974 ;;; useful kinds of "pathname" that might not support wildcards could
975 ;;; include pathname hosts that model unqueryable namespaces like HTTP
976 ;;; URIs, or that model namespaces that it's not convenient to
977 ;;; investigate, such as the namespace of TCP ports that some network
978 ;;; host listens on. I happen to think it a bad idea to try to
979 ;;; shoehorn such namespaces into a pathnames system, but people
980 ;;; sometimes claim to want pathnames for these things.) -- RMK
983 (defun pathname-intersections (one two)
984 (aver (logical-pathname-p one))
985 (aver (logical-pathname-p two))
987 ((intersect-version (one two)
988 (aver (typep one '(or null (member :newest :wild :unspecific)
990 (aver (typep two '(or null (member :newest :wild :unspecific)
995 ((or (null one) (eq one :unspecific)) two)
996 ((or (null two) (eq two :unspecific)) one)
999 (intersect-name/type (one two)
1000 (aver (typep one '(or null (member :wild :unspecific) string)))
1001 (aver (typep two '(or null (member :wild :unspecific) string)))
1003 ((eq one :wild) two)
1004 ((eq two :wild) one)
1005 ((or (null one) (eq one :unspecific)) two)
1006 ((or (null two) (eq two :unspecific)) one)
1007 ((string= one two) one)
1008 (t (return-from pathname-intersections nil))))
1009 (intersect-directory (one two)
1010 (aver (typep one '(or null (member :wild :unspecific) list)))
1011 (aver (typep two '(or null (member :wild :unspecific) list)))
1013 ((eq one :wild) two)
1014 ((eq two :wild) one)
1015 ((or (null one) (eq one :unspecific)) two)
1016 ((or (null two) (eq two :unspecific)) one)
1017 (t (aver (eq (car one) (car two)))
1019 (lambda (x) (cons (car one) x))
1020 (intersect-directory-helper (cdr one) (cdr two)))))))
1021 (let ((version (intersect-version
1022 (pathname-version one) (pathname-version two)))
1023 (name (intersect-name/type
1024 (pathname-name one) (pathname-name two)))
1025 (type (intersect-name/type
1026 (pathname-type one) (pathname-type two)))
1027 (host (pathname-host one)))
1029 (make-pathname :host host :name name :type type
1030 :version version :directory d))
1031 (intersect-directory
1032 (pathname-directory one) (pathname-directory two))))))
1034 ;;; FIXME: written as its own function because I (CSR) don't
1035 ;;; understand it, so helping both debuggability and modularity. In
1036 ;;; case anyone is motivated to rewrite it, it returns a list of
1037 ;;; sublists representing the intersection of the two input directory
1038 ;;; paths (excluding the initial :ABSOLUTE or :RELATIVE).
1040 ;;; FIXME: Does not work with :UP or :BACK
1041 ;;; FIXME: Does not work with patterns
1043 ;;; FIXME: PFD suggests replacing this implementation with a DFA
1044 ;;; conversion of a NDFA. Find out (a) what this means and (b) if it
1045 ;;; turns out to be worth it.
1046 (defun intersect-directory-helper (one two)
1047 (flet ((simple-intersection (cone ctwo)
1049 ((eq cone :wild) ctwo)
1050 ((eq ctwo :wild) cone)
1051 (t (aver (typep cone 'string))
1052 (aver (typep ctwo 'string))
1053 (if (string= cone ctwo) cone nil)))))
1055 ((loop-possible-wild-inferiors-matches
1056 (lower-bound bounding-sequence order)
1057 (let ((index (gensym)) (g2 (gensym)) (g3 (gensym)) (l (gensym)))
1058 `(let ((,l (length ,bounding-sequence)))
1059 (loop for ,index from ,lower-bound to ,l
1060 append (mapcar (lambda (,g2)
1062 (butlast ,bounding-sequence (- ,l ,index))
1067 (if (eq (car (nthcdr ,index ,bounding-sequence))
1071 (intersect-directory-helper
1073 `((nthcdr ,index one) (cdr two))
1074 `((cdr one) (nthcdr ,index two)))))))))))
1076 ((and (eq (car one) :wild-inferiors)
1077 (eq (car two) :wild-inferiors))
1079 (append (mapcar (lambda (x) (cons :wild-inferiors x))
1080 (intersect-directory-helper (cdr one) (cdr two)))
1081 (loop-possible-wild-inferiors-matches 2 one t)
1082 (loop-possible-wild-inferiors-matches 2 two nil))
1084 ((eq (car one) :wild-inferiors)
1085 (delete-duplicates (loop-possible-wild-inferiors-matches 0 two nil)
1087 ((eq (car two) :wild-inferiors)
1088 (delete-duplicates (loop-possible-wild-inferiors-matches 0 one t)
1090 ((and (null one) (null two)) (list nil))
1093 (t (and (simple-intersection (car one) (car two))
1094 (mapcar (lambda (x) (cons (simple-intersection
1095 (car one) (car two)) x))
1096 (intersect-directory-helper (cdr one) (cdr two)))))))))
1098 (defun ensure-directories-exist (pathspec &key verbose (mode #o777))
1100 "Test whether the directories containing the specified file
1101 actually exist, and attempt to create them if they do not.
1102 The MODE argument is a CMUCL/SBCL-specific extension to control
1103 the Unix permission bits."
1104 (let ((pathname (physicalize-pathname (merge-pathnames (pathname pathspec))))
1106 (when (wild-pathname-p pathname)
1107 (error 'simple-file-error
1108 :format-control "bad place for a wild pathname"
1109 :pathname pathspec))
1110 (let ((dir (pathname-directory pathname)))
1111 (loop for i from 1 upto (length dir)
1112 do (let ((newpath (make-pathname
1113 :host (pathname-host pathname)
1114 :device (pathname-device pathname)
1115 :directory (subseq dir 0 i))))
1116 (unless (probe-file newpath)
1117 (let ((namestring (coerce (native-namestring newpath)
1120 (format *standard-output*
1121 "~&creating directory: ~A~%"
1123 (sb!unix:unix-mkdir namestring mode)
1124 (unless (probe-file newpath)
1125 (restart-case (error
1129 "can't create directory ~A"
1130 :format-arguments (list namestring))
1132 :report "Retry directory creation."
1133 (ensure-directories-exist
1135 :verbose verbose :mode mode))
1138 "Continue as if directory creation was successful."
1140 (setf created-p t)))))
1141 (values pathspec created-p))))
1143 (/show0 "filesys.lisp 1000")