make DELETE-FILE respect *DEFAULT-PATHNAME-DEFAULTS*
[sbcl.git] / src / code / filesys.lisp
1 ;;;; file system interface functions -- fairly Unix-centric, but with
2 ;;;; differences between Unix and Win32 papered over.
3
4 ;;;; This software is part of the SBCL system. See the README file for
5 ;;;; more information.
6 ;;;;
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.
12
13 (in-package "SB!IMPL")
14 \f
15 ;;;; Unix pathname host support
16
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.
21 ;;;
22 ;;; Unix namestrings have the following format:
23 ;;;
24 ;;; namestring := [ directory ] [ file [ type [ version ]]]
25 ;;; directory := [ "/" ] { file "/" }*
26 ;;; file := [^/]*
27 ;;; type := "." [^/.]*
28 ;;; version := "." ([0-9]+ | "*")
29 ;;;
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:
34 ;;;
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.
37 ;;;
38 ;;; - Otherwise, the last dot separates the file and the type.
39 ;;;
40 ;;; Wildcard characters:
41 ;;;
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.
45 ;;;
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)
51 ;;;
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)
55   #!+sb-doc
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))
61          (dst 0)
62          (quoted nil))
63     (do ((src start (1+ src)))
64         ((= src end))
65       (cond (quoted
66              (setf (schar result dst) (schar namestr src))
67              (setf quoted nil)
68              (incf dst))
69             (t
70              (let ((char (schar namestr src)))
71                (cond ((char= char #\\)
72                       (setq quoted t))
73                      (t
74                       (setf (schar result dst) char)
75                       (incf dst)))))))
76     (when quoted
77       (error 'namestring-parse-error
78              :complaint "backslash in a bad place"
79              :namestring namestr
80              :offset (1- end)))
81     (%shrink-vector result dst)))
82
83 (defun maybe-make-pattern (namestr start end)
84   (declare (type simple-string namestr)
85            (type index start end))
86   (collect ((pattern))
87     (let ((quoted nil)
88           (any-quotes nil)
89           (last-regular-char nil)
90           (index start))
91       (flet ((flush-pending-regulars ()
92                (when last-regular-char
93                  (pattern (if any-quotes
94                               (remove-backslashes namestr
95                                                   last-regular-char
96                                                   index)
97                               (subseq namestr last-regular-char index)))
98                  (setf any-quotes nil)
99                  (setf last-regular-char nil))))
100         (loop
101           (when (>= index end)
102             (return))
103           (let ((char (schar namestr index)))
104             (cond (quoted
105                    (incf index)
106                    (setf quoted nil))
107                   ((char= char #\\)
108                    (setf quoted t)
109                    (setf any-quotes t)
110                    (unless last-regular-char
111                      (setf last-regular-char index))
112                    (incf index))
113                   ((char= char #\?)
114                    (flush-pending-regulars)
115                    (pattern :single-char-wild)
116                    (incf index))
117                   ((char= char #\*)
118                    (flush-pending-regulars)
119                    (pattern :multi-char-wild)
120                    (incf index))
121                   ((char= char #\[)
122                    (flush-pending-regulars)
123                    (let ((close-bracket
124                           (position #\] namestr :start index :end end)))
125                      (unless close-bracket
126                        (error 'namestring-parse-error
127                               :complaint "#\\[ with no corresponding #\\]"
128                               :namestring namestr
129                               :offset index))
130                      (pattern (cons :character-set
131                                     (subseq namestr
132                                             (1+ index)
133                                             close-bracket)))
134                      (setf index (1+ close-bracket))))
135                   (t
136                    (unless last-regular-char
137                      (setf last-regular-char index))
138                    (incf index)))))
139         (flush-pending-regulars)))
140     (cond ((null (pattern))
141            "")
142           ((null (cdr (pattern)))
143            (let ((piece (first (pattern))))
144              (typecase piece
145                ((member :multi-char-wild) :wild)
146                (simple-string piece)
147                (t
148                 (make-pattern (pattern))))))
149           (t
150            (make-pattern (pattern))))))
151
152 (defun unparse-physical-piece (thing)
153   (etypecase thing
154     ((member :wild) "*")
155     (simple-string
156      (let* ((srclen (length thing))
157             (dstlen srclen))
158        (dotimes (i srclen)
159          (case (schar thing i)
160            ((#\* #\? #\[)
161             (incf dstlen))))
162        (let ((result (make-string dstlen))
163              (dst 0))
164          (dotimes (src srclen)
165            (let ((char (schar thing src)))
166              (case char
167                ((#\* #\? #\[)
168                 (setf (schar result dst) #\\)
169                 (incf dst)))
170              (setf (schar result dst) char)
171              (incf dst)))
172          result)))
173     (pattern
174      (with-output-to-string (s)
175        (dolist (piece (pattern-pieces thing))
176          (etypecase piece
177            (simple-string
178             (write-string piece s))
179            (symbol
180             (ecase piece
181               (:multi-char-wild
182                (write-string "*" s))
183               (:single-char-wild
184                (write-string "?" s))))
185            (cons
186             (case (car piece)
187               (:character-set
188                (write-string "[" s)
189                (write-string (cdr piece) s)
190                (write-string "]" s))
191               (t
192                (error "invalid pattern piece: ~S" piece))))))))))
193
194 (defun make-matcher (piece)
195   (cond ((eq piece :wild)
196          (constantly t))
197         ((typep piece 'pattern)
198          (lambda (other)
199            (when (stringp other)
200              (pattern-matches piece other))))
201         (t
202          (lambda (other)
203            (equal piece other)))))
204
205 (/show0 "filesys.lisp 160")
206
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
211                              :from-end t)))
212     (cond
213       (last-dot
214        (values (maybe-make-pattern namestr start last-dot)
215                (maybe-make-pattern namestr (1+ last-dot) end)
216                :newest))
217       (t
218        (values (maybe-make-pattern namestr start end)
219                nil
220                :newest)))))
221
222 (/show0 "filesys.lisp 200")
223
224 \f
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)
228       #!-win32
229       (sb!unix:unix-lstat namestring)
230       #!+win32
231       (sb!unix:unix-stat namestring)
232     (declare (ignore errno ino))
233     (when existsp
234       (let ((ifmt (logand mode sb!unix:s-ifmt)))
235        (case ifmt
236          (#.sb!unix:s-ifreg :file)
237          (#.sb!unix:s-ifdir :directory)
238          #!-win32
239          (#.sb!unix:s-iflnk :symlink)
240          (t :special))))))
241 \f
242 ;;;; TRUENAME, PROBE-FILE, FILE-AUTHOR, FILE-WRITE-DATE.
243
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:
249 ;;;
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
269 ;;;   routine.
270 ;;;
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
277 ;;; use.
278 (defun query-file-system (pathspec query-for &optional (errorp t))
279   (let ((pathname (translate-logical-pathname
280                    (merge-pathnames
281                     (pathname pathspec)
282                     (sane-default-pathname-defaults)))))
283     (when (wild-pathname-p pathname)
284       (error 'simple-file-error
285              :pathname pathname
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)
290              (if errorp
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
295                                       atime mtime)
296             (sb!unix:unix-stat filename)
297           (declare (ignore ino nlink gid rdev size atime
298                            #!+win32 uid))
299           #!+win32
300           ;; On win32, stat regards UNC pathnames and device names as
301           ;; nonexisting, so we check once more with the native API.
302           (unless existsp
303             (setf existsp
304                   (let ((handle (sb!win32:create-file
305                                  filename 0 0 nil
306                                  sb!win32:file-open-existing
307                                  0 0)))
308                     (when (/= -1 handle)
309                       (setf mode
310                             (or mode
311                                 (if (logbitp 4
312                                              (sb!win32:get-file-attributes filename))
313                                     sb!unix:s-ifdir 0)))
314                       (progn (sb!win32:close-handle handle) t)))))
315           (if existsp
316               (case query-for
317                 (:existence (nth-value
318                              0
319                              (parse-native-namestring
320                               filename
321                               (pathname-host pathname)
322                               (sane-default-pathname-defaults)
323                               :as-directory (eql (logand mode sb!unix:s-ifmt)
324                                                  sb!unix:s-ifdir))))
325                 (:truename (nth-value
326                             0
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)
334                                (if realpath
335                                    realpath
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)
341                                                 sb!unix:s-ifdir))))
342                 (:author
343                  #!-win32
344                  (sb!unix:uid-username uid))
345                 (:write-date (+ unix-to-universal-time mtime)))
346               (progn
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.
354                 #!-win32
355                 (multiple-value-bind (linkp ignore ino mode nlink uid gid rdev
356                                             size atime mtime)
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))
361                              linkp)
362                     (return-from query-file-system
363                       (case query-for
364                         (:existence
365                          ;; We do this reparse so as to return a
366                          ;; normalized pathname.
367                          (parse-native-namestring
368                           filename (pathname-host pathname)))
369                         (:truename
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.
387                          (merge-pathnames
388                           (nth-value
389                            0
390                            (parse-native-namestring
391                             (multiple-value-bind (realpath errno)
392                                 (sb!unix:unix-realpath
393                                  (native-namestring
394                                   (make-pathname
395                                    :name :unspecific
396                                    :type :unspecific
397                                    :version :unspecific
398                                    :defaults (parse-native-namestring
399                                               filename
400                                               (pathname-host pathname)
401                                               (sane-default-pathname-defaults)))))
402                               (if realpath
403                                   realpath
404                                   (fail "couldn't resolve ~A" filename errno)))
405                             (pathname-host pathname)
406                             (sane-default-pathname-defaults)
407                             :as-directory t))
408                           pathname))
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.
412                 (fail
413                  (format nil "failed to find the ~A of ~~A" query-for)
414                  pathspec errno))))))))
415
416
417 (defun probe-file (pathspec)
418   #!+sb-doc
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))
422
423 (defun truename (pathspec)
424   #!+sb-doc
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
429 the stream.
430
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.
434
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)))
443
444 (defun file-author (pathspec)
445   #!+sb-doc
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
448 is a wild pathname."
449   (query-file-system pathspec :author))
450
451 (defun file-write-date (pathspec)
452   #!+sb-doc
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))
457 \f
458 ;;;; miscellaneous other operations
459
460 (/show0 "filesys.lisp 700")
461
462 (defun rename-file (file new-name)
463   #!+sb-doc
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)
470                                             :as-file t)))
471     (unless new-namestring
472       (error 'simple-file-error
473              :pathname new-name
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)
478       (unless res
479         (error 'simple-file-error
480                :pathname new-name
481                :format-control "~@<couldn't rename ~2I~_~A ~I~_to ~2I~_~A: ~
482                                 ~I~_~A~:>"
483                :format-arguments (list original new-name (strerror error))))
484       (when (streamp file)
485         (file-name file new-name))
486       (values new-name original (truename new-name)))))
487
488 (defun delete-file (file)
489   #!+sb-doc
490   "Delete the specified FILE.
491
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)))
499     #!+win32
500     (when (streamp file)
501       (close file))
502     (multiple-value-bind (res err) (sb!unix:unix-unlink namestring)
503       (unless res
504         (simple-file-perror "couldn't delete ~A" namestring err))))
505   t)
506
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.
510
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.
515
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.
518
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
521 exist or is a file."
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
527                                 :files nil
528                                 :directories t
529                                 :classify-symlinks nil)
530                  (map-directory #'delete-file dir
531                                 :files t
532                                 :directories nil
533                                 :classify-symlinks nil)
534                  (delete-dir dir))
535                (delete-dir (dir)
536                  (let* ((namestring (native-namestring dir :as-file t))
537                         (res (alien-funcall (extern-alien #!-win32 "rmdir"
538                                                           #!+win32 "_rmdir"
539                                                           (function int c-string))
540                                             namestring)))
541                    (if (minusp res)
542                        (simple-file-perror "Could not delete directory ~A:~%  ~A"
543                                            namestring (get-errno))
544                        dir))))
545         (if recursive
546             (recurse truename)
547             (delete-dir truename))))))
548 \f
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*
557                                :as-directory t))))
558
559 (defun user-homedir-namestring (&optional username)
560   (if username
561       (sb!unix:user-homedir username)
562       (let ((env-home (posix-getenv "HOME")))
563         (if (and env-home (not (string= env-home "")))
564             env-home
565             #!-win32
566             (sb!unix:uid-homedir (sb!unix:unix-getuid))))))
567
568 ;;; (This is an ANSI Common Lisp function.)
569 (defun user-homedir-pathname (&optional host)
570   #!+sb-doc
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))
576   (values
577    (parse-native-namestring
578     (or (user-homedir-namestring)
579         #!+win32
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*
584     :as-directory t)))
585
586 \f
587 ;;;; DIRECTORY
588
589 (defun directory (pathspec &key (resolve-symlinks t))
590   #!+sb-doc
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
596 matching filenames."
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
600         ;; same truename).
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.  --
610                                    ;; CSR, 2003-10-13
611                                    (query-file-system pathname :truename nil)
612                                    (query-file-system pathname :existence nil))))
613                  (when truename
614                    (setf (gethash (namestring truename) truenames)
615                          truename))))
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
620                       ;; as #p"foo/./".
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
627                   (if (or name type)
628                       (lambda (directory)
629                         (map-matching-entries #'record
630                                               directory
631                                               match-name
632                                               match-type))
633                       #'record)
634                   pathname)))
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
640                          (let ((intersections
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)))
647     (mapcar #'cdr
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))
654                   #'string<
655                   :key #'car))))
656
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)
662                piece))
663            (canonicalize-directory (directory)
664              (let (pieces)
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.
669                      (case (car pieces)
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))
674                                :pathname pathname))
675                        ((:relative :up :back)
676                         (push piece pieces))
677                        (t
678                         (pop pieces)))
679                      (push piece pieces)))
680                (nreverse 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)
685              (cond ((not type)
686                     (make-pathname :name nil :defaults pathname))
687                    ((equal "" type)
688                     (make-pathname :name nil
689                                    :type nil
690                                    :directory (butlast dir)
691                                    :defaults pathname))))
692             (t
693              (make-pathname :name name :type type
694                             :directory dir
695                             :defaults pathname))))))
696
697 ;;; Given a native namestring, provides a WITH-HASH-TABLE-ITERATOR style
698 ;;; interface to mapping over namestrings of entries in the corresponding
699 ;;; directory.
700 (defmacro with-native-directory-iterator ((iterator namestring &key errorp) &body body)
701   (with-unique-names (one-iter)
702     `(dx-flet
703          ((iterate (,one-iter)
704             (declare (type function ,one-iter))
705             (macrolet ((,iterator ()
706                          `(funcall ,',one-iter)))
707               ,@body)))
708        (call-with-native-directory-iterator #'iterate ,namestring ,errorp))))
709
710 (defun call-with-native-directory-iterator (function namestring errorp)
711   (declare (type (or null string) namestring)
712            (function function))
713   (let (dp)
714     (when namestring
715       (dx-flet
716           ((one-iter ()
717              (tagbody
718               :next
719                 (let ((ent (sb!unix:unix-readdir dp nil)))
720                   (when ent
721                     (let ((name (sb!unix:unix-dirent-name ent)))
722                       (when name
723                         (cond ((equal "." name)
724                                (go :next))
725                               ((equal ".." name)
726                                (go :next))
727                               (t
728                                (return-from one-iter name))))))))))
729         (unwind-protect
730              (progn
731                (setf dp (sb!unix:unix-opendir namestring errorp))
732                (when dp
733                  (funcall function #'one-iter)))
734           (when dp
735             (sb!unix:unix-closedir dp nil)))))))
736
737 ;;; This is our core directory access interface that we use to implement
738 ;;; DIRECTORY.
739 (defun map-directory (function directory &key (files t) (directories t)
740                       (classify-symlinks) (errorp t))
741   #!+sb-doc
742   "Map over entries in DIRECTORY. Keyword arguments specify which entries to
743 map over, and how:
744
745  :FILES
746     If true, call FUNCTION with the pathname of each file in DIRECTORY.
747     Defaults to T.
748
749  :DIRECTORIES
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.
754
755  :CLASSIFY-SYMLINKS
756    If T, 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. Defaults to T. In both cases
760    the pathname used for the symbolic link is not fully resolved, but names it
761    as an immediate child of DIRECTORY.
762
763  :ERRORP
764    If true, signal an error if DIRECTORY does not exist, cannot be read, etc.
765    Defaults to T.
766
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
773          ;; network shares.
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)
779                                                  :as-directory t)
780                         (return-from map-directory nil)))
781          (dirname (native-namestring canonical)))
782     (flet ((map-it (name dirp)
783              (funcall fun
784                       (merge-pathnames (parse-native-namestring
785                                         name nil physical
786                                         :as-directory (and dirp (not as-files)))
787                                        physical))))
788       (with-native-directory-iterator (next dirname :errorp errorp)
789        (loop for name = (next)
790              while name
791              do (let* ((full (concatenate 'string dirname name))
792                        (kind (native-file-kind full)))
793                   (when kind
794                     (case kind
795                       (:directory
796                        (when directories
797                          (map-it name t)))
798                       (:symlink
799                        (if classify-symlinks
800                            (let* ((tmpname (merge-pathnames
801                                             (parse-native-namestring
802                                              name nil physical :as-directory nil)
803                                             physical))
804                                   (truename (query-file-system tmpname :truename nil)))
805                              (if (or (not truename)
806                                      (or (pathname-name truename) (pathname-type truename)))
807                                  (when files
808                                    (funcall fun tmpname))
809                                  (when directories
810                                    (map-it name t))))
811                            (when files
812                              (map-it name nil))))
813                       (t
814                        ;; Anything else parses as a file.
815                        (when files
816                          (map-it name nil)))))))))))
817
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)))
825                             dir))
826          (wild-inferiors (position :wild-inferiors dir))
827          (end (cond ((and wild wild-inferiors)
828                      (min wild wild-inferiors))
829                     (t
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)
835                                         :name nil
836                                         :type nil
837                                         :version nil)))
838     (cond (wild-inferiors
839            (map-wild-inferiors function rest starting-point))
840           (wild
841            (map-wild function rest starting-point))
842           (t
843            ;; Nothing wild -- the directory matches itself.
844            (funcall function starting-point))))
845   nil)
846
847 (defun last-directory-piece (pathname)
848   (car (last (pathname-directory pathname))))
849
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))
854         (next (car more)))
855     (flet ((cont (subdirectory)
856              (cond ((not more)
857                     ;; end of the line
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))
863                    (t
864                     (let ((this (pathname-directory subdirectory)))
865                       (map-matching-directories
866                        function
867                        (make-pathname :directory (append this more)
868                                       :defaults subdirectory)))))))
869       (map-directory
870        (if (eq :wild this)
871            #'cont
872            (lambda (sub)
873              (when (pattern-matches this (last-directory-piece sub))
874                (funcall #'cont sub))))
875        directory
876        :files nil
877        :directories t
878        :errorp nil))))
879
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))
884         do (pop more))
885   (let ((next (car more))
886         (rest (cdr more)))
887     (unless more
888       (funcall function directory))
889     (map-directory
890      (cond ((not more)
891             (lambda (pathname)
892               (funcall function pathname)
893               (map-wild-inferiors function more pathname)))
894            (t
895             (lambda (pathname)
896               (let ((this (pathname-directory pathname)))
897                 (when (equal next (car (last this)))
898                   (map-matching-directories
899                    function
900                    (make-pathname :directory (append this rest)
901                                   :defaults pathname)))
902                 (map-wild-inferiors function more pathname)))))
903      directory
904      :files nil
905      :directories t
906      :errorp nil)))
907
908 ;;; Part of DIRECTORY: implements iterating over entries in a directory, and
909 ;;; matching them.
910 (defun map-matching-entries (function directory match-name match-type)
911   (map-directory
912    (lambda (file)
913      (when (and (funcall match-name (pathname-name file))
914                 (funcall match-type (pathname-type file)))
915        (funcall function file)))
916    directory
917    :files t
918    :directories :as-files
919    :errorp nil))
920
921 ;;; NOTE: There is a fair amount of hair below that is probably not
922 ;;; strictly necessary.
923 ;;;
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).
934 ;;;
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.
942
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.
948
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.
962
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
981 ;;; 2007-12-31.
982
983 (defun pathname-intersections (one two)
984   (aver (logical-pathname-p one))
985   (aver (logical-pathname-p two))
986   (labels
987       ((intersect-version (one two)
988          (aver (typep one '(or null (member :newest :wild :unspecific)
989                             integer)))
990          (aver (typep two '(or null (member :newest :wild :unspecific)
991                             integer)))
992          (cond
993            ((eq one :wild) two)
994            ((eq two :wild) one)
995            ((or (null one) (eq one :unspecific)) two)
996            ((or (null two) (eq two :unspecific)) one)
997            ((eql one two) one)
998            (t nil)))
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)))
1002          (cond
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)))
1012          (cond
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)))
1018               (mapcar
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)))
1028       (mapcar (lambda (d)
1029                 (make-pathname :host host :name name :type type
1030                                :version version :directory d))
1031               (intersect-directory
1032                (pathname-directory one) (pathname-directory two))))))
1033
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).
1039 ;;;
1040 ;;; FIXME: Does not work with :UP or :BACK
1041 ;;; FIXME: Does not work with patterns
1042 ;;;
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)
1048            (cond
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)))))
1054     (macrolet
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)
1061                                  (append
1062                                   (butlast ,bounding-sequence (- ,l ,index))
1063                                   ,g2))
1064                         (mapcar
1065                          (lambda (,g3)
1066                            (append
1067                             (if (eq (car (nthcdr ,index ,bounding-sequence))
1068                                     :wild-inferiors)
1069                                 '(:wild-inferiors)
1070                                 nil) ,g3))
1071                          (intersect-directory-helper
1072                           ,@(if order
1073                                 `((nthcdr ,index one) (cdr two))
1074                                 `((cdr one) (nthcdr ,index two)))))))))))
1075       (cond
1076         ((and (eq (car one) :wild-inferiors)
1077               (eq (car two) :wild-inferiors))
1078          (delete-duplicates
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))
1083           :test 'equal))
1084         ((eq (car one) :wild-inferiors)
1085          (delete-duplicates (loop-possible-wild-inferiors-matches 0 two nil)
1086                             :test 'equal))
1087         ((eq (car two) :wild-inferiors)
1088          (delete-duplicates (loop-possible-wild-inferiors-matches 0 one t)
1089                             :test 'equal))
1090         ((and (null one) (null two)) (list nil))
1091         ((null one) nil)
1092         ((null two) 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)))))))))
1097 \f
1098 (defun ensure-directories-exist (pathspec &key verbose (mode #o777))
1099   #!+sb-doc
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))))
1105         (created-p nil))
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)
1118                                              'string)))
1119                      (when verbose
1120                        (format *standard-output*
1121                                "~&creating directory: ~A~%"
1122                                namestring))
1123                      (sb!unix:unix-mkdir namestring mode)
1124                      (unless (probe-file newpath)
1125                        (restart-case (error
1126                                       'simple-file-error
1127                                       :pathname pathspec
1128                                       :format-control
1129                                       "can't create directory ~A"
1130                                       :format-arguments (list namestring))
1131                          (retry ()
1132                            :report "Retry directory creation."
1133                            (ensure-directories-exist
1134                             pathspec
1135                             :verbose verbose :mode mode))
1136                          (continue ()
1137                            :report
1138                            "Continue as if directory creation was successful."
1139                            nil)))
1140                      (setf created-p t)))))
1141       (values pathspec created-p))))
1142
1143 (/show0 "filesys.lisp 1000")