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
301 (:existence (nth-value
303 (parse-native-namestring
305 (pathname-host pathname)
306 (sane-default-pathname-defaults)
307 :as-directory (eql (logand mode sb!unix:s-ifmt)
309 (:truename (nth-value
311 (parse-native-namestring
312 ;; Note: in case the file is stat'able, POSIX
313 ;; realpath(3) gets us a canonical absolute
314 ;; filename, even if the post-merge PATHNAME
315 ;; is not absolute...
316 (multiple-value-bind (realpath errno)
317 (sb!unix:unix-realpath filename)
320 (fail "couldn't resolve ~A" filename errno)))
321 (pathname-host pathname)
322 (sane-default-pathname-defaults)
323 ;; ... but without any trailing slash.
324 :as-directory (eql (logand mode sb!unix:s-ifmt)
328 (sb!unix:uid-username uid))
329 (:write-date (+ unix-to-universal-time mtime)))
331 ;; SBCL has for many years had a policy that a pathname
332 ;; that names an existing, dangling or self-referential
333 ;; symlink denotes the symlink itself. stat(2) fails
334 ;; and sets errno to ENOENT or ELOOP respectively, but
335 ;; we must distinguish cases where the symlink exists
336 ;; from ones where there's a loop in the apparent
337 ;; containing directory.
339 (multiple-value-bind (linkp ignore ino mode nlink uid gid rdev
341 (sb!unix:unix-lstat filename)
342 (declare (ignore ignore ino mode nlink gid rdev size atime))
343 (when (and (or (= errno sb!unix:enoent)
344 (= errno sb!unix:eloop))
346 (return-from query-file-system
349 ;; We do this reparse so as to return a
350 ;; normalized pathname.
351 (parse-native-namestring
352 filename (pathname-host pathname)))
354 ;; So here's a trick: since lstat succeded,
355 ;; FILENAME exists, so its directory exists and
356 ;; only the non-directory part is loopy. So
357 ;; let's resolve FILENAME's directory part with
358 ;; realpath(3), in order to get a canonical
359 ;; absolute name for the directory, and then
360 ;; return a pathname having PATHNAME's name,
361 ;; type, and version, but the rest from the
362 ;; truename of the directory. Since we turned
363 ;; PATHNAME into FILENAME "as a file", FILENAME
364 ;; does not end in a slash, and so we get the
365 ;; directory part of FILENAME by reparsing
366 ;; FILENAME and masking off its name, type, and
367 ;; version bits. But note not to call ourselves
368 ;; recursively, because we don't want to
369 ;; re-merge against *DEFAULT-PATHNAME-DEFAULTS*,
370 ;; since PATHNAME may be a relative pathname.
374 (parse-native-namestring
375 (multiple-value-bind (realpath errno)
376 (sb!unix:unix-realpath
382 :defaults (parse-native-namestring
384 (pathname-host pathname)
385 (sane-default-pathname-defaults)))))
388 (fail "couldn't resolve ~A" filename errno)))
389 (pathname-host pathname)
390 (sane-default-pathname-defaults)
393 (:author (sb!unix:uid-username uid))
394 (:write-date (+ unix-to-universal-time mtime))))))
395 ;; If we're still here, the file doesn't exist; error.
397 (format nil "failed to find the ~A of ~~A" query-for)
398 pathspec errno))))))))
401 (defun probe-file (pathspec)
403 "Return the truename of PATHSPEC if the truename can be found,
404 or NIL otherwise. See TRUENAME for more information."
405 (query-file-system pathspec :truename nil))
407 (defun truename (pathspec)
409 "If PATHSPEC is a pathname that names an existing file, return
410 a pathname that denotes a canonicalized name for the file. If
411 pathspec is a stream associated with a file, return a pathname
412 that denotes a canonicalized name for the file associated with
415 An error of type FILE-ERROR is signalled if no such file exists
416 or if the file system is such that a canonicalized file name
417 cannot be determined or if the pathname is wild.
419 Under Unix, the TRUENAME of a symlink that links to itself or to
420 a file that doesn't exist is considered to be the name of the
421 broken symlink itself."
422 ;; Note that eventually this routine might be different for streams
423 ;; than for other pathname designators.
424 (if (streamp pathspec)
425 (query-file-system pathspec :truename)
426 (query-file-system pathspec :truename)))
428 (defun file-author (pathspec)
430 "Return the author of the file specified by PATHSPEC. Signal an
431 error of type FILE-ERROR if no such file exists, or if PATHSPEC
433 (query-file-system pathspec :author))
435 (defun file-write-date (pathspec)
437 "Return the write date of the file specified by PATHSPEC.
438 An error of type FILE-ERROR is signaled if no such file exists,
439 or if PATHSPEC is a wild pathname."
440 (query-file-system pathspec :write-date))
442 ;;;; miscellaneous other operations
444 (/show0 "filesys.lisp 700")
446 (defun rename-file (file new-name)
448 "Rename FILE to have the specified NEW-NAME. If FILE is a stream open to a
449 file, then the associated file is renamed."
450 (let* ((original (truename file))
451 (original-namestring (native-namestring original :as-file t))
452 (new-name (merge-pathnames new-name original))
453 (new-namestring (native-namestring (physicalize-pathname new-name)
455 (unless new-namestring
456 (error 'simple-file-error
458 :format-control "~S can't be created."
459 :format-arguments (list new-name)))
460 (multiple-value-bind (res error)
461 (sb!unix:unix-rename original-namestring new-namestring)
463 (error 'simple-file-error
465 :format-control "~@<couldn't rename ~2I~_~A ~I~_to ~2I~_~A: ~
467 :format-arguments (list original new-name (strerror error))))
469 (file-name file new-name))
470 (values new-name original (truename new-name)))))
472 (defun delete-file (file)
474 "Delete the specified FILE.
476 If FILE is a stream, on Windows the stream is closed immediately. On Unix
477 plaforms the stream remains open, allowing IO to continue: the OS resources
478 associated with the deleted file remain available till the stream is closed as
479 per standard Unix unlink() behaviour."
480 (let* ((pathname (translate-logical-pathname file))
481 (namestring (native-namestring pathname :as-file t)))
482 (truename file) ; for error-checking side-effect
486 (multiple-value-bind (res err) (sb!unix:unix-unlink namestring)
488 (simple-file-perror "couldn't delete ~A" namestring err))))
491 (defun delete-directory (pathspec &key recursive)
492 "Deletes the directory designated by PATHSPEC (a pathname designator).
493 Returns the truename of the directory deleted.
495 If RECURSIVE is false \(the default), signals an error unless the directory is
496 empty. If RECURSIVE is true, first deletes all files and subdirectories. If
497 RECURSIVE is true and the directory contains symbolic links, the links are
498 deleted, not the files and directories they point to.
500 Signals an error if PATHSPEC designates a file instead of a directory, or if
501 the directory could not be deleted for any reason.
503 \(DELETE-DIRECTORY \"/tmp/foo\") and \(DELETE-DIRECTORY \"/tmp/foo/\") both
504 delete the \"foo\" subdirectory of \"/tmp\", or signal an error if it does not
507 Experimental: interface subject to change."
508 (declare (type pathname-designator pathspec))
509 (with-pathname (pathname pathspec)
510 (let ((truename (truename (translate-logical-pathname pathname))))
511 (labels ((recurse (dir)
512 (map-directory #'recurse dir
515 :classify-symlinks nil)
516 (map-directory #'delete-file dir
519 :classify-symlinks nil)
522 (let* ((namestring (native-namestring dir :as-file t))
523 (res (alien-funcall (extern-alien #!-win32 "rmdir"
525 (function int c-string))
528 (simple-file-perror "Could not delete directory ~A:~% ~A"
529 namestring (get-errno))
533 (delete-dir truename))))))
535 (defun sbcl-homedir-pathname ()
536 (let ((sbcl-home (posix-getenv "SBCL_HOME")))
537 ;; SBCL_HOME isn't set for :EXECUTABLE T embedded cores
538 (when (and sbcl-home (not (string= sbcl-home "")))
539 (parse-native-namestring sbcl-home
540 #!-win32 sb!impl::*unix-host*
541 #!+win32 sb!impl::*win32-host*
542 *default-pathname-defaults*
545 (defun user-homedir-namestring (&optional username)
547 (sb!unix:user-homedir username)
548 (let ((env-home (posix-getenv "HOME")))
549 (if (and env-home (not (string= env-home "")))
552 (sb!unix:uid-homedir (sb!unix:unix-getuid))))))
554 ;;; (This is an ANSI Common Lisp function.)
555 (defun user-homedir-pathname (&optional host)
557 "Return the home directory of the user as a pathname. If the HOME
558 environment variable has been specified, the directory it designates
559 is returned; otherwise obtains the home directory from the operating
560 system. HOST argument is ignored by SBCL."
561 (declare (ignore host))
563 (parse-native-namestring
564 (or (user-homedir-namestring)
566 (sb!win32::get-folder-namestring sb!win32::csidl_profile))
567 #!-win32 sb!impl::*unix-host*
568 #!+win32 sb!impl::*win32-host*
569 *default-pathname-defaults*
575 (defun directory (pathspec &key (resolve-symlinks t))
577 "Return a list of PATHNAMEs, each the TRUENAME of a file that matched the
578 given pathname. Note that the interaction between this ANSI-specified
579 TRUENAMEing and the semantics of the Unix filesystem (symbolic links..) means
580 this function can sometimes return files which don't have the same directory
581 as PATHNAME. If :RESOLVE-SYMLINKS is NIL, don't resolve symbolic links in
583 (let (;; We create one entry in this hash table for each truename,
584 ;; as an asymptotically efficient way of removing duplicates
585 ;; (which can arise when e.g. multiple symlinks map to the
587 (truenames (make-hash-table :test #'equal)))
588 (labels ((record (pathname)
589 (let ((truename (if resolve-symlinks
590 ;; FIXME: Why not not TRUENAME? As reported by
591 ;; Milan Zamazal sbcl-devel 2003-10-05, using
592 ;; TRUENAME causes a race condition whereby
593 ;; removal of a file during the directory
594 ;; operation causes an error. It's not clear
595 ;; what the right thing to do is, though. --
597 (query-file-system pathname :truename nil)
598 (query-file-system pathname :existence nil))))
600 (setf (gethash (namestring truename) truenames)
602 (do-physical-pathnames (pathname)
603 (aver (not (logical-pathname-p pathname)))
604 (let* (;; KLUDGE: Since we don't canonize pathnames on construction,
605 ;; we really have to do it here to get #p"foo/." mean the same
607 (pathname (canonicalize-pathname pathname))
608 (name (pathname-name pathname))
609 (type (pathname-type pathname))
610 (match-name (make-matcher name))
611 (match-type (make-matcher type)))
612 (map-matching-directories
615 (map-matching-entries #'record
621 (do-pathnames (pathname)
622 (if (logical-pathname-p pathname)
623 (let ((host (intern-logical-host (pathname-host pathname))))
624 (dolist (x (logical-host-canon-transls host))
625 (destructuring-bind (from to) x
627 (pathname-intersections pathname from)))
628 (dolist (p intersections)
629 (do-pathnames (translate-pathname p from to)))))))
630 (do-physical-pathnames pathname))))
631 (declare (truly-dynamic-extent #'record))
632 (do-pathnames (merge-pathnames pathspec)))
634 ;; Sorting isn't required by the ANSI spec, but sorting into some
635 ;; canonical order seems good just on the grounds that the
636 ;; implementation should have repeatable behavior when possible.
637 (sort (loop for namestring being each hash-key in truenames
638 using (hash-value truename)
639 collect (cons namestring truename))
643 (defun canonicalize-pathname (pathname)
644 ;; We're really only interested in :UNSPECIFIC -> NIL, :BACK and :UP,
645 ;; and dealing with #p"foo/.." and #p"foo/."
646 (labels ((simplify (piece)
647 (unless (eq :unspecific piece)
649 (canonicalize-directory (directory)
651 (dolist (piece directory)
652 (if (and pieces (member piece '(:back :up)))
653 ;; FIXME: We should really canonicalize when we construct
654 ;; pathnames. This is just wrong.
656 ((:absolute :wild-inferiors)
657 (error 'simple-file-error
658 :format-control "Invalid use of ~S after ~S."
659 :format-arguments (list piece (car pieces))
661 ((:relative :up :back)
665 (push piece pieces)))
667 (let ((name (simplify (pathname-name pathname)))
668 (type (simplify (pathname-type pathname)))
669 (dir (canonicalize-directory (pathname-directory pathname))))
670 (cond ((equal "." name)
672 (make-pathname :name nil :defaults pathname))
674 (make-pathname :name nil
676 :directory (butlast dir)
677 :defaults pathname))))
679 (make-pathname :name name :type type
681 :defaults pathname))))))
683 ;;; Given a native namestring, provides a WITH-HASH-TABLE-ITERATOR style
684 ;;; interface to mapping over namestrings of entries in the corresponding
686 (defmacro with-native-directory-iterator ((iterator namestring &key errorp) &body body)
687 (with-unique-names (one-iter)
689 ((iterate (,one-iter)
690 (declare (type function ,one-iter))
691 (macrolet ((,iterator ()
692 `(funcall ,',one-iter)))
694 (call-with-native-directory-iterator #'iterate ,namestring ,errorp))))
696 (defun call-with-native-directory-iterator (function namestring errorp)
697 (declare (type (or null string) namestring)
705 (let ((ent (sb!unix:unix-readdir dp nil)))
707 (let ((name (sb!unix:unix-dirent-name ent)))
709 (cond ((equal "." name)
714 (return-from one-iter name))))))))))
717 (setf dp (sb!unix:unix-opendir namestring errorp))
719 (funcall function #'one-iter)))
721 (sb!unix:unix-closedir dp nil)))))))
723 ;;; This is our core directory access interface that we use to implement
725 (defun map-directory (function directory &key (files t) (directories t)
726 (classify-symlinks) (errorp t))
728 "Map over entries in DIRECTORY. Keyword arguments specify which entries to
732 If true, call FUNCTION with the pathname of each file in DIRECTORY.
736 If true, call FUNCTION with a pathname for each subdirectory of DIRECTORY.
737 If :AS-FILES, the pathname used is a pathname designating the subdirectory
738 as a file in DIRECTORY. Otherwise the pathname used is a directory
739 pathname. Defaults to T.
742 If T, the decision to call FUNCTION with the pathname of a symbolic link
743 depends on the resolution of the link: if it points to a directory, it is
744 considered a directory entry, otherwise a file entry. If false, all
745 symbolic links are considered file entries. Defaults to T. In both cases
746 the pathname used for the symbolic link is not fully resolved, but names it
747 as an immediate child of DIRECTORY.
750 If true, signal an error if DIRECTORY does not exist, cannot be read, etc.
753 Experimental: interface subject to change."
754 (declare (pathname-designator directory))
755 (let* ((fun (%coerce-callable-to-fun function))
756 (as-files (eq :as-files directories))
757 (physical (physicalize-pathname directory))
758 ;; Not QUERY-FILE-SYSTEM :EXISTENCE, since it doesn't work on Windows
760 (realname (sb!unix:unix-realpath (native-namestring physical :as-file t)))
761 (canonical (if realname
762 (parse-native-namestring realname
763 (pathname-host physical)
764 (sane-default-pathname-defaults)
766 (return-from map-directory nil)))
767 (dirname (native-namestring canonical)))
768 (flet ((map-it (name dirp)
770 (merge-pathnames (parse-native-namestring
772 :as-directory (and dirp (not as-files)))
774 (with-native-directory-iterator (next dirname :errorp errorp)
775 (loop for name = (next)
777 do (let* ((full (concatenate 'string dirname name))
778 (kind (native-file-kind full)))
785 (if classify-symlinks
786 (let* ((tmpname (merge-pathnames
787 (parse-native-namestring
788 name nil physical :as-directory nil)
790 (truename (query-file-system tmpname :truename nil)))
791 (if (or (not truename)
792 (or (pathname-name truename) (pathname-type truename)))
794 (funcall fun tmpname))
800 ;; Anything else parses as a file.
802 (map-it name nil)))))))))))
804 ;;; Part of DIRECTORY: implements matching the directory spec. Calls FUNCTION
805 ;;; with all DIRECTORIES that match the directory portion of PATHSPEC.
806 (defun map-matching-directories (function pathspec)
807 (let* ((dir (pathname-directory pathspec))
808 (length (length dir))
809 (wild (position-if (lambda (elt)
810 (or (eq :wild elt) (typep elt 'pattern)))
812 (wild-inferiors (position :wild-inferiors dir))
813 (end (cond ((and wild wild-inferiors)
814 (min wild wild-inferiors))
816 (or wild wild-inferiors length))))
817 (rest (subseq dir end))
818 (starting-point (make-pathname :directory (subseq dir 0 end)
819 :device (pathname-device pathspec)
820 :host (pathname-host pathspec)
824 (cond (wild-inferiors
825 (map-wild-inferiors function rest starting-point))
827 (map-wild function rest starting-point))
829 ;; Nothing wild -- the directory matches itself.
830 (funcall function starting-point))))
833 (defun last-directory-piece (pathname)
834 (car (last (pathname-directory pathname))))
836 ;;; Part of DIRECTORY: implements iterating over a :WILD or pattern component
837 ;;; in the directory spec.
838 (defun map-wild (function more directory)
839 (let ((this (pop more))
841 (flet ((cont (subdirectory)
844 (funcall function subdirectory))
845 ((or (eq :wild next) (typep next 'pattern))
846 (map-wild function more subdirectory))
847 ((eq :wild-inferiors next)
848 (map-wild-inferiors function more subdirectory))
850 (let ((this (pathname-directory subdirectory)))
851 (map-matching-directories
853 (make-pathname :directory (append this more)
854 :defaults subdirectory)))))))
859 (when (pattern-matches this (last-directory-piece sub))
860 (funcall #'cont sub))))
866 ;;; Part of DIRECTORY: implements iterating over a :WILD-INFERIORS component
867 ;;; in the directory spec.
868 (defun map-wild-inferiors (function more directory)
869 (loop while (member (car more) '(:wild :wild-inferiors))
871 (let ((next (car more))
874 (funcall function directory))
878 (funcall function pathname)
879 (map-wild-inferiors function more pathname)))
882 (let ((this (pathname-directory pathname)))
883 (when (equal next (car (last this)))
884 (map-matching-directories
886 (make-pathname :directory (append this rest)
887 :defaults pathname)))
888 (map-wild-inferiors function more pathname)))))
894 ;;; Part of DIRECTORY: implements iterating over entries in a directory, and
896 (defun map-matching-entries (function directory match-name match-type)
899 (when (and (funcall match-name (pathname-name file))
900 (funcall match-type (pathname-type file)))
901 (funcall function file)))
904 :directories :as-files
907 ;;; NOTE: There is a fair amount of hair below that is probably not
908 ;;; strictly necessary.
910 ;;; The issue is the following: what does (DIRECTORY "SYS:*;") mean?
911 ;;; Until 2004-01, SBCL's behaviour was unquestionably wrong, as it
912 ;;; did not translate the logical pathname at all, but instead treated
913 ;;; it as a physical one. Other Lisps seem to to treat this call as
914 ;;; equivalent to (DIRECTORY (TRANSLATE-LOGICAL-PATHNAME "SYS:*;")),
915 ;;; which is fine as far as it goes, but not very interesting, and
916 ;;; arguably counterintuitive. (PATHNAME-MATCH-P "SYS:SRC;" "SYS:*;")
917 ;;; is true, so why should "SYS:SRC;" not show up in the call to
918 ;;; DIRECTORY? (assuming the physical pathname corresponding to it
919 ;;; exists, of course).
921 ;;; So, the interpretation that I am pushing is for all pathnames
922 ;;; matching the input pathname to be queried. This means that we
923 ;;; need to compute the intersection of the input pathname and the
924 ;;; logical host FROM translations, and then translate the resulting
925 ;;; pathname using the host to the TO translation; this treatment is
926 ;;; recursively invoked until we get a physical pathname, whereupon
927 ;;; our physical DIRECTORY implementation takes over.
929 ;;; FIXME: this is an incomplete implementation. It only works when
930 ;;; both are logical pathnames (which is OK, because that's the only
931 ;;; case when we call it), but there are other pitfalls as well: see
932 ;;; the DIRECTORY-HELPER below for some, but others include a lack of
933 ;;; pattern handling.
935 ;;; The above was written by CSR, I (RMK) believe. The argument that
936 ;;; motivates the interpretation is faulty, however: PATHNAME-MATCH-P
937 ;;; returns true for (PATHNAME-MATCH-P #P"/tmp/*/" #P"/tmp/../"), but
938 ;;; the latter pathname is not in the result of DIRECTORY on the
939 ;;; former. Indeed, if DIRECTORY were constrained to return the
940 ;;; truename for every pathname for which PATHNAME-MATCH-P returned
941 ;;; true and which denoted a filename that named an existing file,
942 ;;; (DIRECTORY #P"/tmp/**/") would be required to list every file on a
943 ;;; Unix system, since any file can be named as though it were "below"
944 ;;; /tmp, given the dotdot entries. So I think the strongest
945 ;;; "consistency" we can define between PATHNAME-MATCH-P and DIRECTORY
946 ;;; is that PATHNAME-MATCH-P returns true of everything DIRECTORY
947 ;;; returns, but not vice versa.
949 ;;; In any case, even if the motivation were sound, DIRECTORY on a
950 ;;; wild logical pathname has no portable semantics. I see nothing in
951 ;;; ANSI that requires implementations to support wild physical
952 ;;; pathnames, and so there need not be any translation of a wild
953 ;;; logical pathname to a phyiscal pathname. So a program that calls
954 ;;; DIRECTORY on a wild logical pathname is doing something
955 ;;; non-portable at best. And if the only sensible semantics for
956 ;;; DIRECTORY on a wild logical pathname is something like the
957 ;;; following, it would be just as well if it signaled an error, since
958 ;;; a program can't possibly rely on the result of an intersection of
959 ;;; user-defined translations with a file system probe. (Potentially
960 ;;; useful kinds of "pathname" that might not support wildcards could
961 ;;; include pathname hosts that model unqueryable namespaces like HTTP
962 ;;; URIs, or that model namespaces that it's not convenient to
963 ;;; investigate, such as the namespace of TCP ports that some network
964 ;;; host listens on. I happen to think it a bad idea to try to
965 ;;; shoehorn such namespaces into a pathnames system, but people
966 ;;; sometimes claim to want pathnames for these things.) -- RMK
969 (defun pathname-intersections (one two)
970 (aver (logical-pathname-p one))
971 (aver (logical-pathname-p two))
973 ((intersect-version (one two)
974 (aver (typep one '(or null (member :newest :wild :unspecific)
976 (aver (typep two '(or null (member :newest :wild :unspecific)
981 ((or (null one) (eq one :unspecific)) two)
982 ((or (null two) (eq two :unspecific)) one)
985 (intersect-name/type (one two)
986 (aver (typep one '(or null (member :wild :unspecific) string)))
987 (aver (typep two '(or null (member :wild :unspecific) string)))
991 ((or (null one) (eq one :unspecific)) two)
992 ((or (null two) (eq two :unspecific)) one)
993 ((string= one two) one)
994 (t (return-from pathname-intersections nil))))
995 (intersect-directory (one two)
996 (aver (typep one '(or null (member :wild :unspecific) list)))
997 (aver (typep two '(or null (member :wild :unspecific) list)))
1000 ((eq two :wild) one)
1001 ((or (null one) (eq one :unspecific)) two)
1002 ((or (null two) (eq two :unspecific)) one)
1003 (t (aver (eq (car one) (car two)))
1005 (lambda (x) (cons (car one) x))
1006 (intersect-directory-helper (cdr one) (cdr two)))))))
1007 (let ((version (intersect-version
1008 (pathname-version one) (pathname-version two)))
1009 (name (intersect-name/type
1010 (pathname-name one) (pathname-name two)))
1011 (type (intersect-name/type
1012 (pathname-type one) (pathname-type two)))
1013 (host (pathname-host one)))
1015 (make-pathname :host host :name name :type type
1016 :version version :directory d))
1017 (intersect-directory
1018 (pathname-directory one) (pathname-directory two))))))
1020 ;;; FIXME: written as its own function because I (CSR) don't
1021 ;;; understand it, so helping both debuggability and modularity. In
1022 ;;; case anyone is motivated to rewrite it, it returns a list of
1023 ;;; sublists representing the intersection of the two input directory
1024 ;;; paths (excluding the initial :ABSOLUTE or :RELATIVE).
1026 ;;; FIXME: Does not work with :UP or :BACK
1027 ;;; FIXME: Does not work with patterns
1029 ;;; FIXME: PFD suggests replacing this implementation with a DFA
1030 ;;; conversion of a NDFA. Find out (a) what this means and (b) if it
1031 ;;; turns out to be worth it.
1032 (defun intersect-directory-helper (one two)
1033 (flet ((simple-intersection (cone ctwo)
1035 ((eq cone :wild) ctwo)
1036 ((eq ctwo :wild) cone)
1037 (t (aver (typep cone 'string))
1038 (aver (typep ctwo 'string))
1039 (if (string= cone ctwo) cone nil)))))
1041 ((loop-possible-wild-inferiors-matches
1042 (lower-bound bounding-sequence order)
1043 (let ((index (gensym)) (g2 (gensym)) (g3 (gensym)) (l (gensym)))
1044 `(let ((,l (length ,bounding-sequence)))
1045 (loop for ,index from ,lower-bound to ,l
1046 append (mapcar (lambda (,g2)
1048 (butlast ,bounding-sequence (- ,l ,index))
1053 (if (eq (car (nthcdr ,index ,bounding-sequence))
1057 (intersect-directory-helper
1059 `((nthcdr ,index one) (cdr two))
1060 `((cdr one) (nthcdr ,index two)))))))))))
1062 ((and (eq (car one) :wild-inferiors)
1063 (eq (car two) :wild-inferiors))
1065 (append (mapcar (lambda (x) (cons :wild-inferiors x))
1066 (intersect-directory-helper (cdr one) (cdr two)))
1067 (loop-possible-wild-inferiors-matches 2 one t)
1068 (loop-possible-wild-inferiors-matches 2 two nil))
1070 ((eq (car one) :wild-inferiors)
1071 (delete-duplicates (loop-possible-wild-inferiors-matches 0 two nil)
1073 ((eq (car two) :wild-inferiors)
1074 (delete-duplicates (loop-possible-wild-inferiors-matches 0 one t)
1076 ((and (null one) (null two)) (list nil))
1079 (t (and (simple-intersection (car one) (car two))
1080 (mapcar (lambda (x) (cons (simple-intersection
1081 (car one) (car two)) x))
1082 (intersect-directory-helper (cdr one) (cdr two)))))))))
1084 (defun ensure-directories-exist (pathspec &key verbose (mode #o777))
1086 "Test whether the directories containing the specified file
1087 actually exist, and attempt to create them if they do not.
1088 The MODE argument is a CMUCL/SBCL-specific extension to control
1089 the Unix permission bits."
1090 (let ((pathname (physicalize-pathname (merge-pathnames (pathname pathspec))))
1092 (when (wild-pathname-p pathname)
1093 (error 'simple-file-error
1094 :format-control "bad place for a wild pathname"
1095 :pathname pathspec))
1096 (let ((dir (pathname-directory pathname)))
1097 (loop for i from 1 upto (length dir)
1098 do (let ((newpath (make-pathname
1099 :host (pathname-host pathname)
1100 :device (pathname-device pathname)
1101 :directory (subseq dir 0 i))))
1102 (unless (probe-file newpath)
1103 (let ((namestring (coerce (native-namestring newpath)
1106 (format *standard-output*
1107 "~&creating directory: ~A~%"
1109 (sb!unix:unix-mkdir namestring mode)
1110 (unless (probe-file newpath)
1111 (restart-case (error
1115 "can't create directory ~A"
1116 :format-arguments (list namestring))
1118 :report "Retry directory creation."
1119 (ensure-directories-exist
1121 :verbose verbose :mode mode))
1124 "Continue as if directory creation was successful."
1126 (setf created-p t)))))
1127 (values pathspec created-p))))
1129 (/show0 "filesys.lisp 1000")