1.0.28.64: more DIRECTORY work
[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           (if existsp
299               (case query-for
300                 (:existence (nth-value
301                              0
302                              (parse-native-namestring
303                               filename
304                               (pathname-host pathname)
305                               (sane-default-pathname-defaults)
306                               :as-directory (eql (logand mode sb!unix:s-ifmt)
307                                                  sb!unix:s-ifdir))))
308                 (:truename (nth-value
309                             0
310                             (parse-native-namestring
311                              ;; Note: in case the file is stat'able, POSIX
312                              ;; realpath(3) gets us a canonical absolute
313                              ;; filename, even if the post-merge PATHNAME
314                              ;; is not absolute...
315                              (multiple-value-bind (realpath errno)
316                                  (sb!unix:unix-realpath filename)
317                                (if realpath
318                                    realpath
319                                    (fail "couldn't resolve ~A" filename errno)))
320                              (pathname-host pathname)
321                              (sane-default-pathname-defaults)
322                              ;; ... but without any trailing slash.
323                              :as-directory (eql (logand  mode sb!unix:s-ifmt)
324                                                 sb!unix:s-ifdir))))
325                 (:author (sb!unix:uid-username uid))
326                 (:write-date (+ unix-to-universal-time mtime)))
327               (progn
328                 ;; SBCL has for many years had a policy that a pathname
329                 ;; that names an existing, dangling or self-referential
330                 ;; symlink denotes the symlink itself.  stat(2) fails
331                 ;; and sets errno to ENOENT or ELOOP respectively, but
332                 ;; we must distinguish cases where the symlink exists
333                 ;; from ones where there's a loop in the apparent
334                 ;; containing directory.
335                 #!-win32
336                 (multiple-value-bind (linkp ignore ino mode nlink uid gid rdev
337                                             size atime mtime)
338                     (sb!unix:unix-lstat filename)
339                   (declare (ignore ignore ino mode nlink gid rdev size atime))
340                   (when (and (or (= errno sb!unix:enoent)
341                                  (= errno sb!unix:eloop))
342                              linkp)
343                     (return-from query-file-system
344                       (case query-for
345                         (:existence
346                          ;; We do this reparse so as to return a
347                          ;; normalized pathname.
348                          (parse-native-namestring
349                           filename (pathname-host pathname)))
350                         (:truename
351                          ;; So here's a trick: since lstat succeded,
352                          ;; FILENAME exists, so its directory exists and
353                          ;; only the non-directory part is loopy.  So
354                          ;; let's resolve FILENAME's directory part with
355                          ;; realpath(3), in order to get a canonical
356                          ;; absolute name for the directory, and then
357                          ;; return a pathname having PATHNAME's name,
358                          ;; type, and version, but the rest from the
359                          ;; truename of the directory.  Since we turned
360                          ;; PATHNAME into FILENAME "as a file", FILENAME
361                          ;; does not end in a slash, and so we get the
362                          ;; directory part of FILENAME by reparsing
363                          ;; FILENAME and masking off its name, type, and
364                          ;; version bits.  But note not to call ourselves
365                          ;; recursively, because we don't want to
366                          ;; re-merge against *DEFAULT-PATHNAME-DEFAULTS*,
367                          ;; since PATHNAME may be a relative pathname.
368                          (merge-pathnames
369                           (nth-value
370                            0
371                            (parse-native-namestring
372                             (multiple-value-bind (realpath errno)
373                                 (sb!unix:unix-realpath
374                                  (native-namestring
375                                   (make-pathname
376                                    :name :unspecific
377                                    :type :unspecific
378                                    :version :unspecific
379                                    :defaults (parse-native-namestring
380                                               filename
381                                               (pathname-host pathname)
382                                               (sane-default-pathname-defaults)))))
383                               (if realpath
384                                   realpath
385                                   (fail "couldn't resolve ~A" filename errno)))
386                             (pathname-host pathname)
387                             (sane-default-pathname-defaults)
388                             :as-directory t))
389                           pathname))
390                         (:author (sb!unix:uid-username uid))
391                         (:write-date (+ unix-to-universal-time mtime))))))
392                 ;; If we're still here, the file doesn't exist; error.
393                 (fail
394                  (format nil "failed to find the ~A of ~~A" query-for)
395                  pathspec errno))))))))
396
397
398 (defun probe-file (pathspec)
399   #!+sb-doc
400   "Return the truename of PATHSPEC if the truename can be found,
401 or NIL otherwise.  See TRUENAME for more information."
402   (query-file-system pathspec :truename nil))
403
404 (defun truename (pathspec)
405   #!+sb-doc
406   "If PATHSPEC is a pathname that names an existing file, return
407 a pathname that denotes a canonicalized name for the file.  If
408 pathspec is a stream associated with a file, return a pathname
409 that denotes a canonicalized name for the file associated with
410 the stream.
411
412 An error of type FILE-ERROR is signalled if no such file exists
413 or if the file system is such that a canonicalized file name
414 cannot be determined or if the pathname is wild.
415
416 Under Unix, the TRUENAME of a symlink that links to itself or to
417 a file that doesn't exist is considered to be the name of the
418 broken symlink itself."
419   ;; Note that eventually this routine might be different for streams
420   ;; than for other pathname designators.
421   (if (streamp pathspec)
422       (query-file-system pathspec :truename)
423       (query-file-system pathspec :truename)))
424
425 (defun file-author (pathspec)
426   #!+sb-doc
427   "Return the author of the file specified by PATHSPEC. Signal an
428 error of type FILE-ERROR if no such file exists, or if PATHSPEC
429 is a wild pathname."
430   (query-file-system pathspec :author))
431
432 (defun file-write-date (pathspec)
433   #!+sb-doc
434   "Return the write date of the file specified by PATHSPEC.
435 An error of type FILE-ERROR is signaled if no such file exists,
436 or if PATHSPEC is a wild pathname."
437   (query-file-system pathspec :write-date))
438 \f
439 ;;;; miscellaneous other operations
440
441 (/show0 "filesys.lisp 700")
442
443 (defun rename-file (file new-name)
444   #!+sb-doc
445   "Rename FILE to have the specified NEW-NAME. If FILE is a stream open to a
446   file, then the associated file is renamed."
447   (let* ((original (truename file))
448          (original-namestring (native-namestring original :as-file t))
449          (new-name (merge-pathnames new-name original))
450          (new-namestring (native-namestring new-name :as-file t)))
451     (unless new-namestring
452       (error 'simple-file-error
453              :pathname new-name
454              :format-control "~S can't be created."
455              :format-arguments (list new-name)))
456     (multiple-value-bind (res error)
457         (sb!unix:unix-rename original-namestring new-namestring)
458       (unless res
459         (error 'simple-file-error
460                :pathname new-name
461                :format-control "~@<couldn't rename ~2I~_~A ~I~_to ~2I~_~A: ~
462                                 ~I~_~A~:>"
463                :format-arguments (list original new-name (strerror error))))
464       (when (streamp file)
465         (file-name file new-name))
466       (values new-name original (truename new-name)))))
467
468 (defun delete-file (file)
469   #!+sb-doc
470   "Delete the specified FILE."
471   (let* ((truename (probe-file file))
472          (namestring (when truename
473                        (native-namestring truename :as-file t))))
474     (when (streamp file)
475       (close file :abort t))
476     (unless namestring
477       (error 'simple-file-error
478              :pathname file
479              :format-control "~S doesn't exist."
480              :format-arguments (list file)))
481     (multiple-value-bind (res err) (sb!unix:unix-unlink namestring)
482       (unless res
483         (simple-file-perror "couldn't delete ~A" namestring err))))
484   t)
485 \f
486 (defun sbcl-homedir-pathname ()
487   (let ((sbcl-home (posix-getenv "SBCL_HOME")))
488     ;; SBCL_HOME isn't set for :EXECUTABLE T embedded cores
489     (when (and sbcl-home (not (string= sbcl-home "")))
490       (parse-native-namestring sbcl-home
491                                #!-win32 sb!impl::*unix-host*
492                                #!+win32 sb!impl::*win32-host*
493                                *default-pathname-defaults*
494                                :as-directory t))))
495
496 ;;; (This is an ANSI Common Lisp function.)
497 (defun user-homedir-pathname (&optional host)
498   #!+sb-doc
499   "Return the home directory of the user as a pathname. If the HOME
500 environment variable has been specified, the directory it designates
501 is returned; otherwise obtains the home directory from the operating
502 system."
503   (declare (ignore host))
504   (let ((env-home (posix-getenv "HOME")))
505     (values
506      (parse-native-namestring
507       (if (and env-home (not (string= env-home "")))
508           env-home
509           #!-win32
510           (sb!unix:uid-homedir (sb!unix:unix-getuid))
511           #!+win32
512           ;; Needs to bypass PARSE-NATIVE-NAMESTRING & ENSURE-TRAILING-SLASH
513           ;; What?! -- RMK, 2007-12-31
514           (return-from user-homedir-pathname
515             (sb!win32::get-folder-pathname sb!win32::csidl_profile)))
516       #!-win32 sb!impl::*unix-host*
517       #!+win32 sb!impl::*win32-host*
518       *default-pathname-defaults*
519       :as-directory t))))
520
521 \f
522 ;;;; DIRECTORY
523
524 (defun directory (pathspec &key (resolve-symlinks t))
525   #!+sb-doc
526   "Return a list of PATHNAMEs, each the TRUENAME of a file that matched the
527 given pathname. Note that the interaction between this ANSI-specified
528 TRUENAMEing and the semantics of the Unix filesystem (symbolic links..) means
529 this function can sometimes return files which don't have the same directory
530 as PATHNAME. If :RESOLVE-SYMLINKS is NIL, don't resolve symbolic links in
531 matching filenames."
532   (let (;; We create one entry in this hash table for each truename,
533         ;; as an asymptotically efficient way of removing duplicates
534         ;; (which can arise when e.g. multiple symlinks map to the
535         ;; same truename).
536         (truenames (make-hash-table :test #'equal)))
537     (labels ((record (pathname)
538                (let ((truename (if resolve-symlinks
539                                    ;; FIXME: Why not not TRUENAME?  As reported by
540                                    ;; Milan Zamazal sbcl-devel 2003-10-05, using
541                                    ;; TRUENAME causes a race condition whereby
542                                    ;; removal of a file during the directory
543                                    ;; operation causes an error.  It's not clear
544                                    ;; what the right thing to do is, though.  --
545                                    ;; CSR, 2003-10-13
546                                    (query-file-system pathname :truename nil)
547                                    (query-file-system pathname :existence nil))))
548                  (when truename
549                    (setf (gethash (namestring truename) truenames)
550                          truename))))
551              (do-physical-pathnames (pathname)
552                (aver (not (logical-pathname-p pathname)))
553                (let* (;; KLUDGE: Since we don't canonize pathnames on construction,
554                       ;; we really have to do it here to get #p"foo/." mean the same
555                       ;; as #p"foo/./".
556                       (pathname (canonicalize-pathname pathname))
557                       (name (pathname-name pathname))
558                       (type (pathname-type pathname))
559                       ;; KLUDGE: We want #p"/foo" to match #p"/foo/,
560                       ;; so cobble up a directory name component from
561                       ;; name and type -- just take care with "*.*"!
562                       (dirname (if (and (eq :wild name) (eq :wild type))
563                                    "*"
564                                    (with-output-to-string (s)
565                                      (when name
566                                        (write-string (unparse-physical-piece name) s))
567                                      (when type
568                                        (write-string "." s)
569                                        (write-string (unparse-physical-piece type) s)))))
570                       (dir (maybe-make-pattern dirname 0 (length dirname)))
571                       (match-name (make-matcher name))
572                       (match-type (make-matcher type))
573                       (match-dir (make-matcher dir)))
574                  (map-matching-directories
575                   (if (or name type)
576                       (lambda (directory)
577                         (map-matching-files #'record
578                                             directory
579                                             match-name
580                                             match-type
581                                             match-dir))
582                       #'record)
583                   pathname)))
584              (do-pathnames (pathname)
585                (if (logical-pathname-p pathname)
586                    (let ((host (intern-logical-host (pathname-host pathname))))
587                      (dolist (x (logical-host-canon-transls host))
588                        (destructuring-bind (from to) x
589                          (let ((intersections
590                                 (pathname-intersections pathname from)))
591                            (dolist (p intersections)
592                              (do-pathnames (translate-pathname p from to)))))))
593                    (do-physical-pathnames pathname))))
594       (declare (truly-dynamic-extent #'record))
595       (do-pathnames (merge-pathnames pathspec)))
596     (mapcar #'cdr
597             ;; Sorting isn't required by the ANSI spec, but sorting into some
598             ;; canonical order seems good just on the grounds that the
599             ;; implementation should have repeatable behavior when possible.
600             (sort (loop for namestring being each hash-key in truenames
601                         using (hash-value truename)
602                         collect (cons namestring truename))
603                   #'string<
604                   :key #'car))))
605
606  (defun canonicalize-pathname (pathname)
607    ;; We're really only interested in :UNSPECIFIC -> NIL,
608    ;; and dealing with #p"foo/.." and #p"foo/."
609    (flet ((simplify (piece)
610             (unless (eq :unspecific piece)
611               piece)))
612      (let ((name (simplify (pathname-name pathname)))
613            (type (simplify (pathname-type pathname)))
614            (dir (pathname-directory pathname)))
615       (cond ((equal "." name)
616              (cond ((not type)
617                     (make-pathname :name nil :defaults pathname))
618                    ((equal "" type)
619                     (make-pathname :name nil
620                                    :type nil
621                                    :directory (butlast dir)
622                                    :defaults pathname))))
623             (t
624              (make-pathname :name name :type type :defaults pathname))))))
625
626
627 ;;; Given a native namestring, provides a WITH-HASH-TABLE-ITERATOR style
628 ;;; interface to mapping over namestrings of entries in the corresponding
629 ;;; directory.
630 (defmacro with-native-directory-iterator ((iterator namestring &key errorp) &body body)
631   (with-unique-names (one-iter)
632     `(dx-flet
633          ((iterate (,one-iter)
634             (declare (type function ,one-iter))
635             (macrolet ((,iterator ()
636                          `(funcall ,',one-iter)))
637               ,@body)))
638        (call-with-native-directory-iterator #'iterate ,namestring ,errorp))))
639
640 (defun call-with-native-directory-iterator (function namestring errorp)
641   (declare (type (or null string) namestring)
642            (function function))
643   (let (dp)
644     (when namestring
645       (dx-flet
646           ((one-iter ()
647              (tagbody
648               :next
649                 (let ((ent (sb!unix:unix-readdir dp nil)))
650                   (when ent
651                     (let ((name (sb!unix:unix-dirent-name ent)))
652                       (when name
653                         (cond ((equal "." name)
654                                (go :next))
655                               ((equal ".." name)
656                                (go :next))
657                               (t
658                                (return-from one-iter name))))))))))
659         (unwind-protect
660              (progn
661                (setf dp (sb!unix:unix-opendir namestring errorp))
662                (when dp
663                  (funcall function #'one-iter)))
664           (when dp
665             (sb!unix:unix-closedir dp nil)))))))
666
667 ;;; This is our core directory access interface that we use to implement
668 ;;; DIRECTORY.
669 (defun map-directory (function directory &key (files t) (directories t) (errorp t))
670   #!+sb-doc
671   "Call FUNCTION with the pathname for each entry in DIRECTORY as follows: if
672 FILES is true (the default), FUNCTION is called for each file in the
673 directory; if DIRECTORIES is true (the default), FUNCTION is called for each
674 subdirectory. If ERRORP is true (the default) signal an error if DIRECTORY
675 does not exist, cannot be read, etc.
676
677 On platforms supporting symbolic links the decision to call FUNCTION with its
678 pathname depends on the resolution of the link: if it points to a directory,
679 it is considered a directory entry. Whether it is considered a file or a
680 directory, the provided pathname is not fully resolved, but rather names the
681 symbolic link as an immediate child of DIRECTORY.
682
683 Experimental: interface subject to change."
684   (let* ((fun (%coerce-callable-to-fun function))
685          (physical (physicalize-pathname directory))
686          ;; Not QUERY-FILE-SYSTEM :EXISTENCE, since it doesn't work on Windows
687          ;; network shares.
688          (realname (sb!unix:unix-realpath (native-namestring physical :as-file t)))
689          (canonical (if realname
690                         (parse-native-namestring realname
691                                                  (pathname-host physical)
692                                                  (sane-default-pathname-defaults)
693                                                  :as-directory t)
694                         (return-from map-directory nil)))
695          (dirname (native-namestring canonical)))
696     (flet ((map-it (name dirp)
697              (funcall fun
698                       (merge-pathnames (parse-native-namestring
699                                         name nil physical :as-directory dirp)
700                                        physical))))
701       (with-native-directory-iterator (next dirname :errorp errorp)
702        (loop for name = (next)
703              while name
704              do (let* ((full (concatenate 'string dirname name))
705                        (kind (native-file-kind full)))
706                   (when kind
707                     (case kind
708                       (:directory
709                        (when directories
710                          (map-it name t)))
711                       (:symlink
712                        (let* ((tmpname (merge-pathnames
713                                         (parse-native-namestring
714                                          name nil physical :as-directory nil)
715                                         physical))
716                               (truename (query-file-system tmpname :truename nil)))
717                          (if (or (not truename)
718                                  (or (pathname-name truename) (pathname-type truename)))
719                              (when files
720                                (funcall fun tmpname))
721                              (when directories
722                                (map-it name t)))))
723                       (t
724                        ;; Anything else parses as a file.
725                        (when files
726                          (map-it name nil)))))))))))
727
728 ;;; Part of DIRECTORY: implements matching the directory spec. Calls FUNCTION
729 ;;; with all DIRECTORIES that match the directory portion of PATHSPEC.
730 (defun map-matching-directories (function pathspec)
731   (let* ((dir (pathname-directory pathspec))
732          (length (length dir))
733          (wild (position-if (lambda (elt)
734                               (or (eq :wild elt) (typep elt 'pattern)))
735                             dir))
736          (wild-inferiors (position :wild-inferiors dir))
737          (end (cond ((and wild wild-inferiors)
738                      (min wild wild-inferiors))
739                     (t
740                      (or wild wild-inferiors length))))
741          (rest (subseq dir end))
742          (starting-point (make-pathname :directory (subseq dir 0 end)
743                                         :device (pathname-device pathspec)
744                                         :host (pathname-host pathspec)
745                                         :name nil
746                                         :type nil
747                                         :version nil)))
748     (cond (wild-inferiors
749            (map-wild-inferiors function rest starting-point))
750           (wild
751            (map-wild function rest starting-point))
752           (t
753            ;; Nothing wild -- the directory matches itself.
754            (funcall function starting-point))))
755   nil)
756
757 (defun last-directory-piece (pathname)
758   (car (last (pathname-directory pathname))))
759
760 ;;; Part of DIRECTORY: implements iterating over a :WILD or pattern component
761 ;;; in the directory spec.
762 (defun map-wild (function more directory)
763   (let ((this (pop more))
764         (next (car more)))
765     (flet ((cont (subdirectory)
766              (cond ((not more)
767                     ;; end of the line
768                     (funcall function subdirectory))
769                    ((or (eq :wild next) (typep next 'pattern))
770                     (lambda (pathname)
771                       (map-wild function more pathname)))
772                    ((eq :wild-inferiors next)
773                     (lambda (pathname)
774                       (map-wild-inferiors function more pathname)))
775                    (t
776                     (lambda (pathname)
777                       (let ((this (pathname-directory pathname)))
778                         (when (equal next (car (last this)))
779                           (map-matching-directories
780                            function
781                            (make-pathname :directory (append this more)
782                                           :defaults pathname)))))))))
783       (map-directory
784        (if (eq :wild this)
785            #'cont
786            (lambda (sub)
787              (awhen (pattern-matches this (last-directory-piece sub))
788                (funcall #'cont it))))
789        directory
790        :files nil
791        :directories t
792        :errorp nil))))
793
794 ;;; Part of DIRECTORY: implements iterating over a :WILD-INFERIORS component
795 ;;; in the directory spec.
796 (defun map-wild-inferiors (function more directory)
797   (loop while (member (car more) '(:wild :wild-inferiors))
798         do (pop more))
799   (let ((next (car more))
800         (rest (cdr more)))
801     (unless more
802       (funcall function directory))
803     (map-directory
804      (cond ((not more)
805             (lambda (pathname)
806               (funcall function pathname)
807               (map-wild-inferiors function more pathname)))
808            (t
809             (lambda (pathname)
810               (let ((this (pathname-directory pathname)))
811                 (when (equal next (car (last this)))
812                   (map-matching-directories
813                    function
814                    (make-pathname :directory (append this rest)
815                                   :defaults pathname)))
816                 (map-wild-inferiors function more pathname)))))
817      directory
818      :files nil
819      :directories t
820      :errorp nil)))
821
822 ;;; Part of DIRECTORY: implements iterating over files in a directory, and matching
823 ;;; them.
824 (defun map-matching-files (function directory match-name match-type match-dir)
825   (map-directory
826    (lambda (file)
827      (let ((pname (pathname-name file))
828            (ptype (pathname-type file)))
829        (when (if (or pname ptype)
830                  (and (funcall match-name pname) (funcall match-type ptype))
831                  (funcall match-dir (last-directory-piece file)))
832          (funcall function file))))
833    directory
834    :files t
835    :directories t
836    :errorp nil))
837
838 ;;; NOTE: There is a fair amount of hair below that is probably not
839 ;;; strictly necessary.
840 ;;;
841 ;;; The issue is the following: what does (DIRECTORY "SYS:*;") mean?
842 ;;; Until 2004-01, SBCL's behaviour was unquestionably wrong, as it
843 ;;; did not translate the logical pathname at all, but instead treated
844 ;;; it as a physical one.  Other Lisps seem to to treat this call as
845 ;;; equivalent to (DIRECTORY (TRANSLATE-LOGICAL-PATHNAME "SYS:*;")),
846 ;;; which is fine as far as it goes, but not very interesting, and
847 ;;; arguably counterintuitive.  (PATHNAME-MATCH-P "SYS:SRC;" "SYS:*;")
848 ;;; is true, so why should "SYS:SRC;" not show up in the call to
849 ;;; DIRECTORY?  (assuming the physical pathname corresponding to it
850 ;;; exists, of course).
851 ;;;
852 ;;; So, the interpretation that I am pushing is for all pathnames
853 ;;; matching the input pathname to be queried.  This means that we
854 ;;; need to compute the intersection of the input pathname and the
855 ;;; logical host FROM translations, and then translate the resulting
856 ;;; pathname using the host to the TO translation; this treatment is
857 ;;; recursively invoked until we get a physical pathname, whereupon
858 ;;; our physical DIRECTORY implementation takes over.
859
860 ;;; FIXME: this is an incomplete implementation.  It only works when
861 ;;; both are logical pathnames (which is OK, because that's the only
862 ;;; case when we call it), but there are other pitfalls as well: see
863 ;;; the DIRECTORY-HELPER below for some, but others include a lack of
864 ;;; pattern handling.
865
866 ;;; The above was written by CSR, I (RMK) believe.  The argument that
867 ;;; motivates the interpretation is faulty, however: PATHNAME-MATCH-P
868 ;;; returns true for (PATHNAME-MATCH-P #P"/tmp/*/" #P"/tmp/../"), but
869 ;;; the latter pathname is not in the result of DIRECTORY on the
870 ;;; former.  Indeed, if DIRECTORY were constrained to return the
871 ;;; truename for every pathname for which PATHNAME-MATCH-P returned
872 ;;; true and which denoted a filename that named an existing file,
873 ;;; (DIRECTORY #P"/tmp/**/") would be required to list every file on a
874 ;;; Unix system, since any file can be named as though it were "below"
875 ;;; /tmp, given the dotdot entries.  So I think the strongest
876 ;;; "consistency" we can define between PATHNAME-MATCH-P and DIRECTORY
877 ;;; is that PATHNAME-MATCH-P returns true of everything DIRECTORY
878 ;;; returns, but not vice versa.
879
880 ;;; In any case, even if the motivation were sound, DIRECTORY on a
881 ;;; wild logical pathname has no portable semantics.  I see nothing in
882 ;;; ANSI that requires implementations to support wild physical
883 ;;; pathnames, and so there need not be any translation of a wild
884 ;;; logical pathname to a phyiscal pathname.  So a program that calls
885 ;;; DIRECTORY on a wild logical pathname is doing something
886 ;;; non-portable at best.  And if the only sensible semantics for
887 ;;; DIRECTORY on a wild logical pathname is something like the
888 ;;; following, it would be just as well if it signaled an error, since
889 ;;; a program can't possibly rely on the result of an intersection of
890 ;;; user-defined translations with a file system probe.  (Potentially
891 ;;; useful kinds of "pathname" that might not support wildcards could
892 ;;; include pathname hosts that model unqueryable namespaces like HTTP
893 ;;; URIs, or that model namespaces that it's not convenient to
894 ;;; investigate, such as the namespace of TCP ports that some network
895 ;;; host listens on.  I happen to think it a bad idea to try to
896 ;;; shoehorn such namespaces into a pathnames system, but people
897 ;;; sometimes claim to want pathnames for these things.)  -- RMK
898 ;;; 2007-12-31.
899
900 (defun pathname-intersections (one two)
901   (aver (logical-pathname-p one))
902   (aver (logical-pathname-p two))
903   (labels
904       ((intersect-version (one two)
905          (aver (typep one '(or null (member :newest :wild :unspecific)
906                             integer)))
907          (aver (typep two '(or null (member :newest :wild :unspecific)
908                             integer)))
909          (cond
910            ((eq one :wild) two)
911            ((eq two :wild) one)
912            ((or (null one) (eq one :unspecific)) two)
913            ((or (null two) (eq two :unspecific)) one)
914            ((eql one two) one)
915            (t nil)))
916        (intersect-name/type (one two)
917          (aver (typep one '(or null (member :wild :unspecific) string)))
918          (aver (typep two '(or null (member :wild :unspecific) string)))
919          (cond
920            ((eq one :wild) two)
921            ((eq two :wild) one)
922            ((or (null one) (eq one :unspecific)) two)
923            ((or (null two) (eq two :unspecific)) one)
924            ((string= one two) one)
925            (t nil)))
926        (intersect-directory (one two)
927          (aver (typep one '(or null (member :wild :unspecific) list)))
928          (aver (typep two '(or null (member :wild :unspecific) list)))
929          (cond
930            ((eq one :wild) two)
931            ((eq two :wild) one)
932            ((or (null one) (eq one :unspecific)) two)
933            ((or (null two) (eq two :unspecific)) one)
934            (t (aver (eq (car one) (car two)))
935               (mapcar
936                (lambda (x) (cons (car one) x))
937                (intersect-directory-helper (cdr one) (cdr two)))))))
938     (let ((version (intersect-version
939                     (pathname-version one) (pathname-version two)))
940           (name (intersect-name/type
941                  (pathname-name one) (pathname-name two)))
942           (type (intersect-name/type
943                  (pathname-type one) (pathname-type two)))
944           (host (pathname-host one)))
945       (mapcar (lambda (d)
946                 (make-pathname :host host :name name :type type
947                                :version version :directory d))
948               (intersect-directory
949                (pathname-directory one) (pathname-directory two))))))
950
951 ;;; FIXME: written as its own function because I (CSR) don't
952 ;;; understand it, so helping both debuggability and modularity.  In
953 ;;; case anyone is motivated to rewrite it, it returns a list of
954 ;;; sublists representing the intersection of the two input directory
955 ;;; paths (excluding the initial :ABSOLUTE or :RELATIVE).
956 ;;;
957 ;;; FIXME: Does not work with :UP or :BACK
958 ;;; FIXME: Does not work with patterns
959 ;;;
960 ;;; FIXME: PFD suggests replacing this implementation with a DFA
961 ;;; conversion of a NDFA.  Find out (a) what this means and (b) if it
962 ;;; turns out to be worth it.
963 (defun intersect-directory-helper (one two)
964   (flet ((simple-intersection (cone ctwo)
965            (cond
966              ((eq cone :wild) ctwo)
967              ((eq ctwo :wild) cone)
968              (t (aver (typep cone 'string))
969                 (aver (typep ctwo 'string))
970                 (if (string= cone ctwo) cone nil)))))
971     (macrolet
972         ((loop-possible-wild-inferiors-matches
973              (lower-bound bounding-sequence order)
974            (let ((index (gensym)) (g2 (gensym)) (g3 (gensym)) (l (gensym)))
975              `(let ((,l (length ,bounding-sequence)))
976                (loop for ,index from ,lower-bound to ,l
977                 append (mapcar (lambda (,g2)
978                                  (append
979                                   (butlast ,bounding-sequence (- ,l ,index))
980                                   ,g2))
981                         (mapcar
982                          (lambda (,g3)
983                            (append
984                             (if (eq (car (nthcdr ,index ,bounding-sequence))
985                                     :wild-inferiors)
986                                 '(:wild-inferiors)
987                                 nil) ,g3))
988                          (intersect-directory-helper
989                           ,@(if order
990                                 `((nthcdr ,index one) (cdr two))
991                                 `((cdr one) (nthcdr ,index two)))))))))))
992       (cond
993         ((and (eq (car one) :wild-inferiors)
994               (eq (car two) :wild-inferiors))
995          (delete-duplicates
996           (append (mapcar (lambda (x) (cons :wild-inferiors x))
997                           (intersect-directory-helper (cdr one) (cdr two)))
998                   (loop-possible-wild-inferiors-matches 2 one t)
999                   (loop-possible-wild-inferiors-matches 2 two nil))
1000           :test 'equal))
1001         ((eq (car one) :wild-inferiors)
1002          (delete-duplicates (loop-possible-wild-inferiors-matches 0 two nil)
1003                             :test 'equal))
1004         ((eq (car two) :wild-inferiors)
1005          (delete-duplicates (loop-possible-wild-inferiors-matches 0 one t)
1006                             :test 'equal))
1007         ((and (null one) (null two)) (list nil))
1008         ((null one) nil)
1009         ((null two) nil)
1010         (t (and (simple-intersection (car one) (car two))
1011                 (mapcar (lambda (x) (cons (simple-intersection
1012                                            (car one) (car two)) x))
1013                         (intersect-directory-helper (cdr one) (cdr two)))))))))
1014 \f
1015 (defun ensure-directories-exist (pathspec &key verbose (mode #o777))
1016   #!+sb-doc
1017   "Test whether the directories containing the specified file
1018   actually exist, and attempt to create them if they do not.
1019   The MODE argument is a CMUCL/SBCL-specific extension to control
1020   the Unix permission bits."
1021   (let ((pathname (physicalize-pathname (merge-pathnames (pathname pathspec))))
1022         (created-p nil))
1023     (when (wild-pathname-p pathname)
1024       (error 'simple-file-error
1025              :format-control "bad place for a wild pathname"
1026              :pathname pathspec))
1027     (let ((dir (pathname-directory pathname)))
1028       (loop for i from 1 upto (length dir)
1029             do (let ((newpath (make-pathname
1030                                :host (pathname-host pathname)
1031                                :device (pathname-device pathname)
1032                                :directory (subseq dir 0 i))))
1033                  (unless (probe-file newpath)
1034                    (let ((namestring (coerce (native-namestring newpath)
1035                                              'string)))
1036                      (when verbose
1037                        (format *standard-output*
1038                                "~&creating directory: ~A~%"
1039                                namestring))
1040                      (sb!unix:unix-mkdir namestring mode)
1041                      (unless (probe-file newpath)
1042                        (restart-case (error
1043                                       'simple-file-error
1044                                       :pathname pathspec
1045                                       :format-control
1046                                       "can't create directory ~A"
1047                                       :format-arguments (list namestring))
1048                          (retry ()
1049                            :report "Retry directory creation."
1050                            (ensure-directories-exist
1051                             pathspec
1052                             :verbose verbose :mode mode))
1053                          (continue ()
1054                            :report
1055                            "Continue as if directory creation was successful."
1056                            nil)))
1057                      (setf created-p t)))))
1058       (values pathspec created-p))))
1059
1060 (/show0 "filesys.lisp 1000")