0.9.16.17:
[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 (defvar *ignore-wildcards* nil)
84
85 (/show0 "filesys.lisp 86")
86
87 (defun maybe-make-pattern (namestr start end)
88   (declare (type simple-string namestr)
89            (type index start end))
90   (if *ignore-wildcards*
91       (subseq namestr start end)
92       (collect ((pattern))
93         (let ((quoted nil)
94               (any-quotes nil)
95               (last-regular-char nil)
96               (index start))
97           (flet ((flush-pending-regulars ()
98                    (when last-regular-char
99                      (pattern (if any-quotes
100                                   (remove-backslashes namestr
101                                                       last-regular-char
102                                                       index)
103                                   (subseq namestr last-regular-char index)))
104                      (setf any-quotes nil)
105                      (setf last-regular-char nil))))
106             (loop
107               (when (>= index end)
108                 (return))
109               (let ((char (schar namestr index)))
110                 (cond (quoted
111                        (incf index)
112                        (setf quoted nil))
113                       ((char= char #\\)
114                        (setf quoted t)
115                        (setf any-quotes t)
116                        (unless last-regular-char
117                          (setf last-regular-char index))
118                        (incf index))
119                       ((char= char #\?)
120                        (flush-pending-regulars)
121                        (pattern :single-char-wild)
122                        (incf index))
123                       ((char= char #\*)
124                        (flush-pending-regulars)
125                        (pattern :multi-char-wild)
126                        (incf index))
127                       ((char= char #\[)
128                        (flush-pending-regulars)
129                        (let ((close-bracket
130                               (position #\] namestr :start index :end end)))
131                          (unless close-bracket
132                            (error 'namestring-parse-error
133                                   :complaint "#\\[ with no corresponding #\\]"
134                                   :namestring namestr
135                                   :offset index))
136                          (pattern (cons :character-set
137                                         (subseq namestr
138                                                 (1+ index)
139                                                 close-bracket)))
140                          (setf index (1+ close-bracket))))
141                       (t
142                        (unless last-regular-char
143                          (setf last-regular-char index))
144                        (incf index)))))
145             (flush-pending-regulars)))
146         (cond ((null (pattern))
147                "")
148               ((null (cdr (pattern)))
149                (let ((piece (first (pattern))))
150                  (typecase piece
151                    ((member :multi-char-wild) :wild)
152                    (simple-string piece)
153                    (t
154                     (make-pattern (pattern))))))
155               (t
156                (make-pattern (pattern)))))))
157
158 (/show0 "filesys.lisp 160")
159
160 (defun extract-name-type-and-version (namestr start end)
161   (declare (type simple-string namestr)
162            (type index start end))
163   (let* ((last-dot (position #\. namestr :start (1+ start) :end end
164                              :from-end t)))
165     (cond
166       (last-dot
167        (values (maybe-make-pattern namestr start last-dot)
168                (maybe-make-pattern namestr (1+ last-dot) end)
169                :newest))
170       (t
171        (values (maybe-make-pattern namestr start end)
172                nil
173                :newest)))))
174
175 (/show0 "filesys.lisp 200")
176
177 \f
178 ;;;; wildcard matching stuff
179
180 ;;; Return a list of all the Lispy filenames (not including e.g. the
181 ;;; Unix magic "." and "..") in the directory named by DIRECTORY-NAME.
182 (defun directory-lispy-filenames (directory-name)
183   (with-alien ((adlf (* c-string)
184                      (alien-funcall (extern-alien
185                                      "alloc_directory_lispy_filenames"
186                                      (function (* c-string) c-string))
187                                     directory-name)))
188     (if (null-alien adlf)
189         (error 'simple-file-error
190                :pathname directory-name
191                :format-control "~@<couldn't read directory ~S: ~2I~_~A~:>"
192                :format-arguments (list directory-name (strerror)))
193         (unwind-protect
194             (c-strings->string-list adlf)
195           (alien-funcall (extern-alien "free_directory_lispy_filenames"
196                                        (function void (* c-string)))
197                          adlf)))))
198
199 (/show0 "filesys.lisp 498")
200
201 (defmacro !enumerate-matches ((var pathname &optional result
202                                    &key (verify-existence t)
203                                    (follow-links t))
204                               &body body)
205   `(block nil
206      (%enumerate-matches (pathname ,pathname)
207                          ,verify-existence
208                          ,follow-links
209                          (lambda (,var) ,@body))
210      ,result))
211
212 (/show0 "filesys.lisp 500")
213
214 ;;; Call FUNCTION on matches.
215 ;;;
216 ;;; KLUDGE: this assumes that an absolute pathname is indicated to the
217 ;;; operating system by having a directory separator as the first
218 ;;; character in the directory part.  This is true for Win32 pathnames
219 ;;; and for Unix pathnames, but it isn't true for LispM pathnames (and
220 ;;; their bastard offspring, logical pathnames.  Also it assumes that
221 ;;; Unix pathnames have an empty or :unspecific device, and that
222 ;;; windows drive letters are the only kinds of non-empty/:UNSPECIFIC
223 ;;; devices.
224 (defun %enumerate-matches (pathname verify-existence follow-links function)
225   (/noshow0 "entering %ENUMERATE-MATCHES")
226   (when (pathname-type pathname)
227     (unless (pathname-name pathname)
228       (error "cannot supply a type without a name:~%  ~S" pathname)))
229   (when (and (integerp (pathname-version pathname))
230              (member (pathname-type pathname) '(nil :unspecific)))
231     (error "cannot supply a version without a type:~%  ~S" pathname))
232   (let ((host (pathname-host pathname))
233         (device (pathname-device pathname))
234         (directory (pathname-directory pathname)))
235     (/noshow0 "computed HOST and DIRECTORY")
236     (let* ((dirstring (if directory
237                           (ecase (first directory)
238                             (:absolute (host-unparse-directory-separator host))
239                             (:relative ""))
240                           ""))
241            (devstring (if (and device (not (eq device :unspecific)))
242                           (concatenate 'simple-string (string device) (string #\:))
243                           ""))
244            (headstring (concatenate 'simple-string devstring dirstring)))
245       (if directory
246           (%enumerate-directories headstring (rest directory) pathname
247                                   verify-existence follow-links nil function)
248           (%enumerate-files headstring pathname verify-existence function)))))
249
250 ;;; Call FUNCTION on directories.
251 (defun %enumerate-directories (head tail pathname verify-existence
252                                follow-links nodes function
253                                &aux (host (pathname-host pathname)))
254   (declare (simple-string head))
255   (macrolet ((unix-xstat (name)
256                `(if follow-links
257                     (sb!unix:unix-stat ,name)
258                     (sb!unix:unix-lstat ,name)))
259              (with-directory-node-noted ((head) &body body)
260                `(multiple-value-bind (res dev ino mode)
261                     (unix-xstat ,head)
262                   (when (and res (eql (logand mode sb!unix:s-ifmt)
263                                       sb!unix:s-ifdir))
264                     (let ((nodes (cons (cons dev ino) nodes)))
265                       ,@body))))
266              (with-directory-node-removed ((head) &body body)
267                `(multiple-value-bind (res dev ino mode)
268                     (unix-xstat ,head)
269                   (when (and res (eql (logand mode sb!unix:s-ifmt)
270                                       sb!unix:s-ifdir))
271                     (let ((nodes (remove (cons dev ino) nodes :test #'equal)))
272                       ,@body)))))
273     (if tail
274         (let ((piece (car tail)))
275           (etypecase piece
276             (simple-string
277              (let ((head (concatenate 'string head piece)))
278                (with-directory-node-noted (head)
279                  (%enumerate-directories
280                   (concatenate 'string head
281                                (host-unparse-directory-separator host))
282                   (cdr tail) pathname
283                   verify-existence follow-links
284                   nodes function))))
285             ((member :wild-inferiors)
286              ;; now with extra error case handling from CLHS
287              ;; 19.2.2.4.3 -- CSR, 2004-01-24
288              (when (member (cadr tail) '(:up :back))
289                (error 'simple-file-error
290                       :pathname pathname
291                       :format-control "~@<invalid use of ~S after :WILD-INFERIORS~@:>."
292                       :format-arguments (list (cadr tail))))
293              (%enumerate-directories head (rest tail) pathname
294                                      verify-existence follow-links
295                                      nodes function)
296              (dolist (name (directory-lispy-filenames head))
297                (let ((subdir (concatenate 'string head name)))
298                  (multiple-value-bind (res dev ino mode)
299                      (unix-xstat subdir)
300                    (declare (type (or fixnum null) mode))
301                    (when (and res (eql (logand mode sb!unix:s-ifmt)
302                                        sb!unix:s-ifdir))
303                      (unless (dolist (dir nodes nil)
304                                (when (and (eql (car dir) dev)
305                                           (eql (cdr dir) ino))
306                                  (return t)))
307                        (let ((nodes (cons (cons dev ino) nodes))
308                              (subdir (concatenate 'string subdir (host-unparse-directory-separator host))))
309                          (%enumerate-directories subdir tail pathname
310                                                  verify-existence follow-links
311                                                  nodes function))))))))
312             ((or pattern (member :wild))
313              (dolist (name (directory-lispy-filenames head))
314                (when (or (eq piece :wild) (pattern-matches piece name))
315                  (let ((subdir (concatenate 'string head name)))
316                    (multiple-value-bind (res dev ino mode)
317                        (unix-xstat subdir)
318                      (declare (type (or fixnum null) mode))
319                      (when (and res
320                                 (eql (logand mode sb!unix:s-ifmt)
321                                      sb!unix:s-ifdir))
322                        (let ((nodes (cons (cons dev ino) nodes))
323                              (subdir (concatenate 'string subdir (host-unparse-directory-separator host))))
324                          (%enumerate-directories subdir (rest tail) pathname
325                                                  verify-existence follow-links
326                                                  nodes function))))))))
327           ((member :up)
328            (when (string= head (host-unparse-directory-separator host))
329              (error 'simple-file-error
330                     :pathname pathname
331                     :format-control "~@<invalid use of :UP after :ABSOLUTE.~@:>"))
332            (with-directory-node-removed (head)
333              (let ((head (concatenate 'string head "..")))
334                (with-directory-node-noted (head)
335                  (%enumerate-directories (concatenate 'string head (host-unparse-directory-separator host))
336                                          (rest tail) pathname
337                                          verify-existence follow-links
338                                          nodes function)))))
339           ((member :back)
340            ;; :WILD-INFERIORS is handled above, so the only case here
341            ;; should be (:ABSOLUTE :BACK)
342            (aver (string= head (host-unparse-directory-separator host)))
343            (error 'simple-file-error
344                   :pathname pathname
345                   :format-control "~@<invalid use of :BACK after :ABSOLUTE.~@:>"))))
346         (%enumerate-files head pathname verify-existence function))))
347
348 ;;; Call FUNCTION on files.
349 (defun %enumerate-files (directory pathname verify-existence function)
350   (declare (simple-string directory))
351   (/noshow0 "entering %ENUMERATE-FILES")
352   (let ((name (%pathname-name pathname))
353         (type (%pathname-type pathname))
354         (version (%pathname-version pathname)))
355     (/noshow0 "computed NAME, TYPE, and VERSION")
356     (cond ((member name '(nil :unspecific))
357            (/noshow0 "UNSPECIFIC, more or less")
358            (let ((directory (coerce directory 'string)))
359              (when (or (not verify-existence)
360                        (sb!unix:unix-file-kind directory))
361                (funcall function directory))))
362           ((or (pattern-p name)
363                (pattern-p type)
364                (eq name :wild)
365                (eq type :wild))
366            (/noshow0 "WILD, more or less")
367            ;; I IGNORE-ERRORS here just because the original CMU CL
368            ;; code did. I think the intent is that it's not an error
369            ;; to request matches to a wild pattern when no matches
370            ;; exist, but I haven't tried to figure out whether
371            ;; everything is kosher. (E.g. what if we try to match a
372            ;; wildcard but we don't have permission to read one of the
373            ;; relevant directories?) -- WHN 2001-04-17
374            (dolist (complete-filename (ignore-errors
375                                         (directory-lispy-filenames directory)))
376              (multiple-value-bind
377                  (file-name file-type file-version)
378                  (let ((*ignore-wildcards* t))
379                    (extract-name-type-and-version
380                     complete-filename 0 (length complete-filename)))
381                (when (and (components-match file-name name)
382                           (components-match file-type type)
383                           (components-match file-version version))
384                  (funcall function
385                           (concatenate 'string
386                                        directory
387                                        complete-filename))))))
388           (t
389            (/noshow0 "default case")
390            (let ((file (concatenate 'string directory name)))
391              (/noshow "computed basic FILE")
392              (unless (or (null type) (eq type :unspecific))
393                (/noshow0 "tweaking FILE for more-or-less-:UNSPECIFIC case")
394                (setf file (concatenate 'string file "." type)))
395              (unless (member version '(nil :newest :wild :unspecific))
396                (/noshow0 "tweaking FILE for more-or-less-:WILD case")
397                (setf file (concatenate 'string file "."
398                                        (quick-integer-to-string version))))
399              (/noshow0 "finished possibly tweaking FILE")
400              (when (or (not verify-existence)
401                        (sb!unix:unix-file-kind file t))
402                (/noshow0 "calling FUNCTION on FILE")
403                (funcall function file)))))))
404
405 (/noshow0 "filesys.lisp 603")
406
407 ;;; FIXME: Why do we need this?
408 (defun quick-integer-to-string (n)
409   (declare (type integer n))
410   (cond ((not (fixnump n))
411          (write-to-string n :base 10 :radix nil))
412         ((zerop n) "0")
413         ((eql n 1) "1")
414         ((minusp n)
415          (concatenate 'simple-base-string "-"
416                       (the simple-base-string (quick-integer-to-string (- n)))))
417         (t
418          (do* ((len (1+ (truncate (integer-length n) 3)))
419                (res (make-string len :element-type 'base-char))
420                (i (1- len) (1- i))
421                (q n)
422                (r 0))
423               ((zerop q)
424                (incf i)
425                (replace res res :start2 i :end2 len)
426                (%shrink-vector res (- len i)))
427            (declare (simple-string res)
428                     (fixnum len i r q))
429            (multiple-value-setq (q r) (truncate q 10))
430            (setf (schar res i) (schar "0123456789" r))))))
431 \f
432 ;;;; UNIX-NAMESTRING
433
434 (defun empty-relative-pathname-spec-p (x)
435   (or (equal x "")
436       (and (pathnamep x)
437            (or (equal (pathname-directory x) '(:relative))
438                ;; KLUDGE: I'm not sure this second check should really
439                ;; have to be here. But on sbcl-0.6.12.7,
440                ;; (PATHNAME-DIRECTORY (PATHNAME "")) is NIL, and
441                ;; (PATHNAME "") seems to act like an empty relative
442                ;; pathname, so in order to work with that, I test
443                ;; for NIL here. -- WHN 2001-05-18
444                (null (pathname-directory x)))
445            (null (pathname-name x))
446            (null (pathname-type x)))
447       ;; (The ANSI definition of "pathname specifier" has
448       ;; other cases, but none of them seem to admit the possibility
449       ;; of being empty and relative.)
450       ))
451
452 ;;; Convert PATHNAME into a string that can be used with UNIX system
453 ;;; calls, or return NIL if no match is found. Wild-cards are expanded.
454 ;;;
455 ;;; FIXME: apart from the error checking (for wildness and for
456 ;;; existence) and conversion to physical pathanme, this is redundant
457 ;;; with UNPARSE-NATIVE-UNIX-NAMESTRING; one should probably be
458 ;;; written in terms of the other.
459 ;;;
460 ;;; FIXME: actually this (I think) works not just for Unix.
461 (defun unix-namestring (pathname-spec &optional (for-input t))
462   (let* ((namestring (physicalize-pathname (merge-pathnames pathname-spec)))
463          (matches nil)) ; an accumulator for actual matches
464     (when (wild-pathname-p namestring)
465       (error 'simple-file-error
466              :pathname namestring
467              :format-control "bad place for a wild pathname"))
468     (!enumerate-matches (match namestring nil :verify-existence for-input)
469                         (push match matches))
470     (case (length matches)
471       (0 nil)
472       (1 (first matches))
473       (t (bug "!ENUMERATE-MATCHES returned more than one match on a non-wild pathname")))))
474 \f
475 ;;;; TRUENAME and PROBE-FILE
476
477 ;;; This is only trivially different from PROBE-FILE, which is silly
478 ;;; but ANSI.
479 (defun truename (pathname)
480   #!+sb-doc
481   "Return the pathname for the actual file described by PATHNAME.
482   An error of type FILE-ERROR is signalled if no such file exists,
483   or the pathname is wild.
484
485   Under Unix, the TRUENAME of a broken symlink is considered to be
486   the name of the broken symlink itself."
487   (let ((result (probe-file pathname)))
488     (unless result
489       (error 'simple-file-error
490              :pathname pathname
491              :format-control "The file ~S does not exist."
492              :format-arguments (list (namestring pathname))))
493     result))
494
495 (defun probe-file (pathname)
496   #!+sb-doc
497   "Return a pathname which is the truename of the file if it exists, or NIL
498   otherwise. An error of type FILE-ERROR is signaled if pathname is wild."
499   (let* ((defaulted-pathname (merge-pathnames
500                               pathname
501                               (sane-default-pathname-defaults)))
502          (namestring (unix-namestring defaulted-pathname t)))
503     (when (and namestring (sb!unix:unix-file-kind namestring t))
504       (let ((trueishname (sb!unix:unix-resolve-links namestring)))
505         (when trueishname
506           (let* ((*ignore-wildcards* t)
507                  (name (sb!unix:unix-simplify-pathname trueishname)))
508             (if (eq (sb!unix:unix-file-kind name) :directory)
509                 ;; FIXME: this might work, but it's ugly.
510                 (pathname (concatenate 'string name "/"))
511                 (pathname name))))))))
512 \f
513 ;;;; miscellaneous other operations
514
515 (/show0 "filesys.lisp 700")
516
517 (defun rename-file (file new-name)
518   #!+sb-doc
519   "Rename FILE to have the specified NEW-NAME. If FILE is a stream open to a
520   file, then the associated file is renamed."
521   (let* ((original (truename file))
522          (original-namestring (unix-namestring original t))
523          (new-name (merge-pathnames new-name original))
524          (new-namestring (unix-namestring new-name nil)))
525     (unless new-namestring
526       (error 'simple-file-error
527              :pathname new-name
528              :format-control "~S can't be created."
529              :format-arguments (list new-name)))
530     (multiple-value-bind (res error)
531         (sb!unix:unix-rename original-namestring new-namestring)
532       (unless res
533         (error 'simple-file-error
534                :pathname new-name
535                :format-control "~@<couldn't rename ~2I~_~A ~I~_to ~2I~_~A: ~
536                                 ~I~_~A~:>"
537                :format-arguments (list original new-name (strerror error))))
538       (when (streamp file)
539         (file-name file new-name))
540       (values new-name original (truename new-name)))))
541
542 (defun delete-file (file)
543   #!+sb-doc
544   "Delete the specified FILE."
545   (let ((namestring (unix-namestring file t)))
546     (when (streamp file)
547       (close file :abort t))
548     (unless namestring
549       (error 'simple-file-error
550              :pathname file
551              :format-control "~S doesn't exist."
552              :format-arguments (list file)))
553     (multiple-value-bind (res err) (sb!unix:unix-unlink namestring)
554       (unless res
555         (simple-file-perror "couldn't delete ~A" namestring err))))
556   t)
557 \f
558 (defun ensure-trailing-slash (string)
559   (let ((last-char (char string (1- (length string)))))
560          (if (or (eql last-char #\/)
561                  #!+win32
562                  (eql last-char #\\))
563              string
564              (concatenate 'string string "/"))))
565
566 (defun sbcl-homedir-pathname ()
567   (let ((sbcl-home (posix-getenv "SBCL_HOME")))
568     ;; SBCL_HOME isn't set for :EXECUTABLE T embedded cores
569     (when sbcl-home
570       (parse-native-namestring
571        (ensure-trailing-slash sbcl-home)))))
572
573 ;;; (This is an ANSI Common Lisp function.)
574 (defun user-homedir-pathname (&optional host)
575   #!+sb-doc
576   "Return the home directory of the user as a pathname. If the HOME
577 environment variable has been specified, the directory it designates
578 is returned; otherwise obtains the home directory from the operating
579 system."
580   (declare (ignore host))
581   (parse-native-namestring
582    (ensure-trailing-slash
583     (if (posix-getenv "HOME")
584         (posix-getenv "HOME")
585         #!-win32
586         (sb!unix:uid-homedir (sb!unix:unix-getuid))
587         #!+win32
588         ;; Needs to bypass PARSE-NATIVE-NAMESTRING & ENSURE-TRAILING-SLASH
589         (return-from user-homedir-pathname
590           (sb!win32::get-folder-pathname sb!win32::csidl_profile))))))
591
592 (defun file-write-date (file)
593   #!+sb-doc
594   "Return file's creation date, or NIL if it doesn't exist.
595  An error of type file-error is signaled if file is a wild pathname"
596   (let ((name (unix-namestring file t)))
597     (when name
598       (multiple-value-bind
599             (res dev ino mode nlink uid gid rdev size atime mtime)
600           (sb!unix:unix-stat name)
601         (declare (ignore dev ino mode nlink uid gid rdev size atime))
602         (when res
603           (+ unix-to-universal-time mtime))))))
604
605 (defun file-author (file)
606   #!+sb-doc
607   "Return the file author as a string, or NIL if the author cannot be
608  determined. Signal an error of type FILE-ERROR if FILE doesn't exist,
609  or FILE is a wild pathname."
610   (let ((name (unix-namestring (pathname file) t)))
611     (unless name
612       (error 'simple-file-error
613              :pathname file
614              :format-control "~S doesn't exist."
615              :format-arguments (list file)))
616     (multiple-value-bind (winp dev ino mode nlink uid)
617         (sb!unix:unix-stat name)
618       (declare (ignore dev ino mode nlink))
619       (and winp (sb!unix:uid-username uid)))))
620 \f
621 ;;;; DIRECTORY
622
623 (/show0 "filesys.lisp 800")
624
625 ;;; NOTE: There is a fair amount of hair below that is probably not
626 ;;; strictly necessary.
627 ;;;
628 ;;; The issue is the following: what does (DIRECTORY "SYS:*;") mean?
629 ;;; Until 2004-01, SBCL's behaviour was unquestionably wrong, as it
630 ;;; did not translate the logical pathname at all, but instead treated
631 ;;; it as a physical one.  Other Lisps seem to to treat this call as
632 ;;; equivalent to (DIRECTORY (TRANSLATE-LOGICAL-PATHNAME "SYS:*;")),
633 ;;; which is fine as far as it goes, but not very interesting, and
634 ;;; arguably counterintuitive.  (PATHNAME-MATCH-P "SYS:SRC;" "SYS:*;")
635 ;;; is true, so why should "SYS:SRC;" not show up in the call to
636 ;;; DIRECTORY?  (assuming the physical pathname corresponding to it
637 ;;; exists, of course).
638 ;;;
639 ;;; So, the interpretation that I am pushing is for all pathnames
640 ;;; matching the input pathname to be queried.  This means that we
641 ;;; need to compute the intersection of the input pathname and the
642 ;;; logical host FROM translations, and then translate the resulting
643 ;;; pathname using the host to the TO translation; this treatment is
644 ;;; recursively invoked until we get a physical pathname, whereupon
645 ;;; our physical DIRECTORY implementation takes over.
646
647 ;;; FIXME: this is an incomplete implementation.  It only works when
648 ;;; both are logical pathnames (which is OK, because that's the only
649 ;;; case when we call it), but there are other pitfalls as well: see
650 ;;; the DIRECTORY-HELPER below for some, but others include a lack of
651 ;;; pattern handling.
652 (defun pathname-intersections (one two)
653   (aver (logical-pathname-p one))
654   (aver (logical-pathname-p two))
655   (labels
656       ((intersect-version (one two)
657          (aver (typep one '(or null (member :newest :wild :unspecific)
658                             integer)))
659          (aver (typep two '(or null (member :newest :wild :unspecific)
660                             integer)))
661          (cond
662            ((eq one :wild) two)
663            ((eq two :wild) one)
664            ((or (null one) (eq one :unspecific)) two)
665            ((or (null two) (eq two :unspecific)) one)
666            ((eql one two) one)
667            (t nil)))
668        (intersect-name/type (one two)
669          (aver (typep one '(or null (member :wild :unspecific) string)))
670          (aver (typep two '(or null (member :wild :unspecific) string)))
671          (cond
672            ((eq one :wild) two)
673            ((eq two :wild) one)
674            ((or (null one) (eq one :unspecific)) two)
675            ((or (null two) (eq two :unspecific)) one)
676            ((string= one two) one)
677            (t nil)))
678        (intersect-directory (one two)
679          (aver (typep one '(or null (member :wild :unspecific) list)))
680          (aver (typep two '(or null (member :wild :unspecific) list)))
681          (cond
682            ((eq one :wild) two)
683            ((eq two :wild) one)
684            ((or (null one) (eq one :unspecific)) two)
685            ((or (null two) (eq two :unspecific)) one)
686            (t (aver (eq (car one) (car two)))
687               (mapcar
688                (lambda (x) (cons (car one) x))
689                (intersect-directory-helper (cdr one) (cdr two)))))))
690     (let ((version (intersect-version
691                     (pathname-version one) (pathname-version two)))
692           (name (intersect-name/type
693                  (pathname-name one) (pathname-name two)))
694           (type (intersect-name/type
695                  (pathname-type one) (pathname-type two)))
696           (host (pathname-host one)))
697       (mapcar (lambda (d)
698                 (make-pathname :host host :name name :type type
699                                :version version :directory d))
700               (intersect-directory
701                (pathname-directory one) (pathname-directory two))))))
702
703 ;;; FIXME: written as its own function because I (CSR) don't
704 ;;; understand it, so helping both debuggability and modularity.  In
705 ;;; case anyone is motivated to rewrite it, it returns a list of
706 ;;; sublists representing the intersection of the two input directory
707 ;;; paths (excluding the initial :ABSOLUTE or :RELATIVE).
708 ;;;
709 ;;; FIXME: Does not work with :UP or :BACK
710 ;;; FIXME: Does not work with patterns
711 ;;;
712 ;;; FIXME: PFD suggests replacing this implementation with a DFA
713 ;;; conversion of a NDFA.  Find out (a) what this means and (b) if it
714 ;;; turns out to be worth it.
715 (defun intersect-directory-helper (one two)
716   (flet ((simple-intersection (cone ctwo)
717            (cond
718              ((eq cone :wild) ctwo)
719              ((eq ctwo :wild) cone)
720              (t (aver (typep cone 'string))
721                 (aver (typep ctwo 'string))
722                 (if (string= cone ctwo) cone nil)))))
723     (macrolet
724         ((loop-possible-wild-inferiors-matches
725              (lower-bound bounding-sequence order)
726            (let ((index (gensym)) (g2 (gensym)) (g3 (gensym)) (l (gensym)))
727              `(let ((,l (length ,bounding-sequence)))
728                (loop for ,index from ,lower-bound to ,l
729                 append (mapcar (lambda (,g2)
730                                  (append
731                                   (butlast ,bounding-sequence (- ,l ,index))
732                                   ,g2))
733                         (mapcar
734                          (lambda (,g3)
735                            (append
736                             (if (eq (car (nthcdr ,index ,bounding-sequence))
737                                     :wild-inferiors)
738                                 '(:wild-inferiors)
739                                 nil) ,g3))
740                          (intersect-directory-helper
741                           ,@(if order
742                                 `((nthcdr ,index one) (cdr two))
743                                 `((cdr one) (nthcdr ,index two)))))))))))
744       (cond
745         ((and (eq (car one) :wild-inferiors)
746               (eq (car two) :wild-inferiors))
747          (delete-duplicates
748           (append (mapcar (lambda (x) (cons :wild-inferiors x))
749                           (intersect-directory-helper (cdr one) (cdr two)))
750                   (loop-possible-wild-inferiors-matches 2 one t)
751                   (loop-possible-wild-inferiors-matches 2 two nil))
752           :test 'equal))
753         ((eq (car one) :wild-inferiors)
754          (delete-duplicates (loop-possible-wild-inferiors-matches 0 two nil)
755                             :test 'equal))
756         ((eq (car two) :wild-inferiors)
757          (delete-duplicates (loop-possible-wild-inferiors-matches 0 one t)
758                             :test 'equal))
759         ((and (null one) (null two)) (list nil))
760         ((null one) nil)
761         ((null two) nil)
762         (t (and (simple-intersection (car one) (car two))
763                 (mapcar (lambda (x) (cons (simple-intersection
764                                            (car one) (car two)) x))
765                         (intersect-directory-helper (cdr one) (cdr two)))))))))
766
767 (defun directory (pathname &key)
768   #!+sb-doc
769   "Return a list of PATHNAMEs, each the TRUENAME of a file that matched the
770    given pathname. Note that the interaction between this ANSI-specified
771    TRUENAMEing and the semantics of the Unix filesystem (symbolic links..)
772    means this function can sometimes return files which don't have the same
773    directory as PATHNAME."
774   (let (;; We create one entry in this hash table for each truename,
775         ;; as an asymptotically efficient way of removing duplicates
776         ;; (which can arise when e.g. multiple symlinks map to the
777         ;; same truename).
778         (truenames (make-hash-table :test #'equal))
779         ;; FIXME: Possibly this MERGE-PATHNAMES call should only
780         ;; happen once we get a physical pathname.
781         (merged-pathname (merge-pathnames pathname)))
782     (labels ((do-physical-directory (pathname)
783                (aver (not (logical-pathname-p pathname)))
784                (!enumerate-matches (match pathname)
785                  (let* ((*ignore-wildcards* t)
786                         ;; FIXME: Why not TRUENAME?  As reported by
787                         ;; Milan Zamazal sbcl-devel 2003-10-05, using
788                         ;; TRUENAME causes a race condition whereby
789                         ;; removal of a file during the directory
790                         ;; operation causes an error.  It's not clear
791                         ;; what the right thing to do is, though.  --
792                         ;; CSR, 2003-10-13
793                         (truename (probe-file match)))
794                    (when truename
795                      (setf (gethash (namestring truename) truenames)
796                            truename)))))
797              (do-directory (pathname)
798                (if (logical-pathname-p pathname)
799                    (let ((host (intern-logical-host (pathname-host pathname))))
800                      (dolist (x (logical-host-canon-transls host))
801                        (destructuring-bind (from to) x
802                          (let ((intersections
803                                 (pathname-intersections pathname from)))
804                            (dolist (p intersections)
805                              (do-directory (translate-pathname p from to)))))))
806                    (do-physical-directory pathname))))
807       (do-directory merged-pathname))
808     (mapcar #'cdr
809             ;; Sorting isn't required by the ANSI spec, but sorting
810             ;; into some canonical order seems good just on the
811             ;; grounds that the implementation should have repeatable
812             ;; behavior when possible.
813             (sort (loop for name being each hash-key in truenames
814                         using (hash-value truename)
815                         collect (cons name truename))
816                   #'string<
817                   :key #'car))))
818 \f
819 (/show0 "filesys.lisp 899")
820
821 ;;; predicate to order pathnames by; goes by name
822 (defun pathname-order (x y)
823   (let ((xn (%pathname-name x))
824         (yn (%pathname-name y)))
825     (if (and xn yn)
826         (let ((res (string-lessp xn yn)))
827           (cond ((not res) nil)
828                 ((= res (length (the simple-string xn))) t)
829                 ((= res (length (the simple-string yn))) nil)
830                 (t t)))
831         xn)))
832 \f
833 (defun ensure-directories-exist (pathspec &key verbose (mode #o777))
834   #!+sb-doc
835   "Test whether the directories containing the specified file
836   actually exist, and attempt to create them if they do not.
837   The MODE argument is a CMUCL/SBCL-specific extension to control
838   the Unix permission bits."
839   (let ((pathname (physicalize-pathname (merge-pathnames (pathname pathspec))))
840         (created-p nil))
841     (when (wild-pathname-p pathname)
842       (error 'simple-file-error
843              :format-control "bad place for a wild pathname"
844              :pathname pathspec))
845     (let ((dir (pathname-directory pathname)))
846       (loop for i from 1 upto (length dir)
847             do (let ((newpath (make-pathname
848                                :host (pathname-host pathname)
849                                :device (pathname-device pathname)
850                                :directory (subseq dir 0 i))))
851                  (unless (probe-file newpath)
852                    (let ((namestring (coerce (namestring newpath) 'string)))
853                      (when verbose
854                        (format *standard-output*
855                                "~&creating directory: ~A~%"
856                                namestring))
857                      (sb!unix:unix-mkdir namestring mode)
858                      (unless (probe-file namestring)
859                        (restart-case (error 'simple-file-error
860                                             :pathname pathspec
861                                             :format-control "can't create directory ~A"
862                                             :format-arguments (list namestring))
863                          (retry ()
864                            :report "Retry directory creation."
865                            (ensure-directories-exist pathspec :verbose verbose :mode mode))
866                          (continue ()
867                            :report "Continue as if directory creation was successful."
868                            nil)))
869                      (setf created-p t)))))
870       (values pathspec created-p))))
871
872 (/show0 "filesys.lisp 1000")