0.8.7.22:
[sbcl.git] / src / code / filesys.lisp
1 ;;;; file system interface functions -- fairly Unix-specific
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!IMPL")
13 \f
14 ;;;; Unix pathname host support
15
16 ;;; Unix namestrings have the following format:
17 ;;;
18 ;;; namestring := [ directory ] [ file [ type [ version ]]]
19 ;;; directory := [ "/" ] { file "/" }*
20 ;;; file := [^/]*
21 ;;; type := "." [^/.]*
22 ;;; version := "." ([0-9]+ | "*")
23 ;;;
24 ;;; Note: this grammar is ambiguous. The string foo.bar.5 can be
25 ;;; parsed as either just the file specified or as specifying the
26 ;;; file, type, and version. Therefore, we use the following rules
27 ;;; when confronted with an ambiguous file.type.version string:
28 ;;;
29 ;;; - If the first character is a dot, it's part of the file. It is not
30 ;;; considered a dot in the following rules.
31 ;;;
32 ;;; - If there is only one dot, it separates the file and the type.
33 ;;;
34 ;;; - If there are multiple dots and the stuff following the last dot
35 ;;; is a valid version, then that is the version and the stuff between
36 ;;; the second to last dot and the last dot is the type.
37 ;;;
38 ;;; Wildcard characters:
39 ;;;
40 ;;; If the directory, file, type components contain any of the
41 ;;; following characters, it is considered part of a wildcard pattern
42 ;;; and has the following meaning.
43 ;;;
44 ;;; ? - matches any character
45 ;;; * - matches any zero or more characters.
46 ;;; [abc] - matches any of a, b, or c.
47 ;;; {str1,str2,...,strn} - matches any of str1, str2, ..., or strn.
48 ;;;
49 ;;; Any of these special characters can be preceded by a backslash to
50 ;;; cause it to be treated as a regular character.
51 (defun remove-backslashes (namestr start end)
52   #!+sb-doc
53   "Remove any occurrences of #\\ from the string because we've already
54    checked for whatever they may have protected."
55   (declare (type simple-base-string namestr)
56            (type index start end))
57   (let* ((result (make-string (- end start) :element-type 'base-char))
58          (dst 0)
59          (quoted nil))
60     (do ((src start (1+ src)))
61         ((= src end))
62       (cond (quoted
63              (setf (schar result dst) (schar namestr src))
64              (setf quoted nil)
65              (incf dst))
66             (t
67              (let ((char (schar namestr src)))
68                (cond ((char= char #\\)
69                       (setq quoted t))
70                      (t
71                       (setf (schar result dst) char)
72                       (incf dst)))))))
73     (when quoted
74       (error 'namestring-parse-error
75              :complaint "backslash in a bad place"
76              :namestring namestr
77              :offset (1- end)))
78     (shrink-vector result dst)))
79
80 (defvar *ignore-wildcards* nil)
81
82 (/show0 "filesys.lisp 86")
83
84 (defun maybe-make-pattern (namestr start end)
85   (declare (type simple-base-string namestr)
86            (type index start end))
87   (if *ignore-wildcards*
88       (subseq namestr start end)
89       (collect ((pattern))
90         (let ((quoted nil)
91               (any-quotes nil)
92               (last-regular-char nil)
93               (index start))
94           (flet ((flush-pending-regulars ()
95                    (when last-regular-char
96                      (pattern (if any-quotes
97                                   (remove-backslashes namestr
98                                                       last-regular-char
99                                                       index)
100                                   (subseq namestr last-regular-char index)))
101                      (setf any-quotes nil)
102                      (setf last-regular-char nil))))
103             (loop
104               (when (>= index end)
105                 (return))
106               (let ((char (schar namestr index)))
107                 (cond (quoted
108                        (incf index)
109                        (setf quoted nil))
110                       ((char= char #\\)
111                        (setf quoted t)
112                        (setf any-quotes t)
113                        (unless last-regular-char
114                          (setf last-regular-char index))
115                        (incf index))
116                       ((char= char #\?)
117                        (flush-pending-regulars)
118                        (pattern :single-char-wild)
119                        (incf index))
120                       ((char= char #\*)
121                        (flush-pending-regulars)
122                        (pattern :multi-char-wild)
123                        (incf index))
124                       ((char= char #\[)
125                        (flush-pending-regulars)
126                        (let ((close-bracket
127                               (position #\] namestr :start index :end end)))
128                          (unless close-bracket
129                            (error 'namestring-parse-error
130                                   :complaint "#\\[ with no corresponding #\\]"
131                                   :namestring namestr
132                                   :offset index))
133                          (pattern (list :character-set
134                                         (subseq namestr
135                                                 (1+ index)
136                                                 close-bracket)))
137                          (setf index (1+ close-bracket))))
138                       (t
139                        (unless last-regular-char
140                          (setf last-regular-char index))
141                        (incf index)))))
142             (flush-pending-regulars)))
143         (cond ((null (pattern))
144                "")
145               ((null (cdr (pattern)))
146                (let ((piece (first (pattern))))
147                  (typecase piece
148                    ((member :multi-char-wild) :wild)
149                    (simple-string piece)
150                    (t
151                     (make-pattern (pattern))))))
152               (t
153                (make-pattern (pattern)))))))
154
155 (/show0 "filesys.lisp 160")
156
157 (defun extract-name-type-and-version (namestr start end)
158   (declare (type simple-base-string namestr)
159            (type index start end))
160   (let* ((last-dot (position #\. namestr :start (1+ start) :end end
161                              :from-end t)))
162     (cond 
163       (last-dot
164        (values (maybe-make-pattern namestr start last-dot)
165                (maybe-make-pattern namestr (1+ last-dot) end)
166                :newest))
167       (t
168        (values (maybe-make-pattern namestr start end)
169                nil
170                :newest)))))
171
172 (/show0 "filesys.lisp 200")
173
174 ;;; Take a string and return a list of cons cells that mark the char
175 ;;; separated subseq. The first value is true if absolute directories
176 ;;; location.
177 (defun split-at-slashes (namestr start end)
178   (declare (type simple-base-string namestr)
179            (type index start end))
180   (let ((absolute (and (/= start end)
181                        (char= (schar namestr start) #\/))))
182     (when absolute
183       (incf start))
184     ;; Next, split the remainder into slash-separated chunks.
185     (collect ((pieces))
186       (loop
187         (let ((slash (position #\/ namestr :start start :end end)))
188           (pieces (cons start (or slash end)))
189           (unless slash
190             (return))
191           (setf start (1+ slash))))
192       (values absolute (pieces)))))
193
194 (defun parse-unix-namestring (namestr start end)
195   (declare (type simple-base-string namestr)
196            (type index start end))
197   (multiple-value-bind (absolute pieces) (split-at-slashes namestr start end)
198     (multiple-value-bind (name type version)
199         (let* ((tail (car (last pieces)))
200                (tail-start (car tail))
201                (tail-end (cdr tail)))
202           (unless (= tail-start tail-end)
203             (setf pieces (butlast pieces))
204             (extract-name-type-and-version namestr tail-start tail-end)))
205
206       (when (stringp name)
207         (let ((position (position-if (lambda (char)
208                                        (or (char= char (code-char 0))
209                                            (char= char #\/)))
210                                      name)))
211           (when position
212             (error 'namestring-parse-error
213                    :complaint "can't embed #\\Nul or #\\/ in Unix namestring"
214                    :namestring namestr
215                    :offset position))))
216       ;; Now we have everything we want. So return it.
217       (values nil ; no host for Unix namestrings
218               nil ; no device for Unix namestrings
219               (collect ((dirs))
220                 (dolist (piece pieces)
221                   (let ((piece-start (car piece))
222                         (piece-end (cdr piece)))
223                     (unless (= piece-start piece-end)
224                       (cond ((string= namestr ".."
225                                       :start1 piece-start
226                                       :end1 piece-end)
227                              (dirs :up))
228                             ((string= namestr "**"
229                                       :start1 piece-start
230                                       :end1 piece-end)
231                              (dirs :wild-inferiors))
232                             (t
233                              (dirs (maybe-make-pattern namestr
234                                                        piece-start
235                                                        piece-end)))))))
236                 (cond (absolute
237                        (cons :absolute (dirs)))
238                       ((dirs)
239                        (cons :relative (dirs)))
240                       (t
241                        nil)))
242               name
243               type
244               version))))
245
246 (/show0 "filesys.lisp 300")
247
248 (defun unparse-unix-host (pathname)
249   (declare (type pathname pathname)
250            (ignore pathname))
251   ;; this host designator needs to be recognized as a physical host in
252   ;; PARSE-NAMESTRING. Until sbcl-0.7.3.x, we had "Unix" here, but
253   ;; that's a valid Logical Hostname, so that's a bad choice. -- CSR,
254   ;; 2002-05-09
255   "")
256
257 (defun unparse-unix-piece (thing)
258   (etypecase thing
259     ((member :wild) "*")
260     (simple-string
261      (let* ((srclen (length thing))
262             (dstlen srclen))
263        (dotimes (i srclen)
264          (case (schar thing i)
265            ((#\* #\? #\[)
266             (incf dstlen))))
267        (let ((result (make-string dstlen))
268              (dst 0))
269          (dotimes (src srclen)
270            (let ((char (schar thing src)))
271              (case char
272                ((#\* #\? #\[)
273                 (setf (schar result dst) #\\)
274                 (incf dst)))
275              (setf (schar result dst) char)
276              (incf dst)))
277          result)))
278     (pattern
279      (collect ((strings))
280        (dolist (piece (pattern-pieces thing))
281          (etypecase piece
282            (simple-string
283             (strings piece))
284            (symbol
285             (ecase piece
286               (:multi-char-wild
287                (strings "*"))
288               (:single-char-wild
289                (strings "?"))))
290            (cons
291             (case (car piece)
292               (:character-set
293                (strings "[")
294                (strings (cdr piece))
295                (strings "]"))
296               (t
297                (error "invalid pattern piece: ~S" piece))))))
298        (apply #'concatenate
299               'simple-string
300               (strings))))))
301
302 (defun unparse-unix-directory-list (directory)
303   (declare (type list directory))
304   (collect ((pieces))
305     (when directory
306       (ecase (pop directory)
307         (:absolute
308          (pieces "/"))
309         (:relative
310          ;; nothing special
311          ))
312       (dolist (dir directory)
313         (typecase dir
314           ((member :up)
315            (pieces "../"))
316           ((member :back)
317            (error ":BACK cannot be represented in namestrings."))
318           ((member :wild-inferiors)
319            (pieces "**/"))
320           ((or simple-string pattern)
321            (pieces (unparse-unix-piece dir))
322            (pieces "/"))
323           (t
324            (error "invalid directory component: ~S" dir)))))
325     (apply #'concatenate 'simple-string (pieces))))
326
327 (defun unparse-unix-directory (pathname)
328   (declare (type pathname pathname))
329   (unparse-unix-directory-list (%pathname-directory pathname)))
330
331 (defun unparse-unix-file (pathname)
332   (declare (type pathname pathname))
333   (collect ((strings))
334     (let* ((name (%pathname-name pathname))
335            (type (%pathname-type pathname))
336            (type-supplied (not (or (null type) (eq type :unspecific)))))
337       ;; Note: by ANSI 19.3.1.1.5, we ignore the version slot when
338       ;; translating logical pathnames to a filesystem without
339       ;; versions (like Unix).
340       (when name
341         (when (and (null type) (position #\. name :start 1))
342           (error "too many dots in the name: ~S" pathname))
343         (strings (unparse-unix-piece name)))
344       (when type-supplied
345         (unless name
346           (error "cannot specify the type without a file: ~S" pathname))
347         (when (typep type 'simple-base-string)
348           (when (position #\. type)
349             (error "type component can't have a #\. inside: ~S" pathname)))
350         (strings ".")
351         (strings (unparse-unix-piece type))))
352     (apply #'concatenate 'simple-string (strings))))
353
354 (/show0 "filesys.lisp 406")
355
356 (defun unparse-unix-namestring (pathname)
357   (declare (type pathname pathname))
358   (concatenate 'simple-string
359                (unparse-unix-directory pathname)
360                (unparse-unix-file pathname)))
361
362 (defun unparse-unix-enough (pathname defaults)
363   (declare (type pathname pathname defaults))
364   (flet ((lose ()
365            (error "~S cannot be represented relative to ~S."
366                   pathname defaults)))
367     (collect ((strings))
368       (let* ((pathname-directory (%pathname-directory pathname))
369              (defaults-directory (%pathname-directory defaults))
370              (prefix-len (length defaults-directory))
371              (result-directory
372               (cond ((and (> prefix-len 1)
373                           (>= (length pathname-directory) prefix-len)
374                           (compare-component (subseq pathname-directory
375                                                      0 prefix-len)
376                                              defaults-directory))
377                      ;; Pathname starts with a prefix of default. So
378                      ;; just use a relative directory from then on out.
379                      (cons :relative (nthcdr prefix-len pathname-directory)))
380                     ((eq (car pathname-directory) :absolute)
381                      ;; We are an absolute pathname, so we can just use it.
382                      pathname-directory)
383                     (t
384                      ;; We are a relative directory. So we lose.
385                      (lose)))))
386         (strings (unparse-unix-directory-list result-directory)))
387       (let* ((pathname-type (%pathname-type pathname))
388              (type-needed (and pathname-type
389                                (not (eq pathname-type :unspecific))))
390              (pathname-name (%pathname-name pathname))
391              (name-needed (or type-needed
392                               (and pathname-name
393                                    (not (compare-component pathname-name
394                                                            (%pathname-name
395                                                             defaults)))))))
396         (when name-needed
397           (unless pathname-name (lose))
398           (when (and (null pathname-type)
399                      (position #\. pathname-name :start 1))
400             (error "too many dots in the name: ~S" pathname))
401           (strings (unparse-unix-piece pathname-name)))
402         (when type-needed
403           (when (or (null pathname-type) (eq pathname-type :unspecific))
404             (lose))
405           (when (typep pathname-type 'simple-base-string)
406             (when (position #\. pathname-type)
407               (error "type component can't have a #\. inside: ~S" pathname)))
408           (strings ".")
409           (strings (unparse-unix-piece pathname-type))))
410       (apply #'concatenate 'simple-string (strings)))))
411 \f
412 ;;;; wildcard matching stuff
413
414 ;;; Return a list of all the Lispy filenames (not including e.g. the
415 ;;; Unix magic "." and "..") in the directory named by DIRECTORY-NAME.
416 (defun directory-lispy-filenames (directory-name)
417   (with-alien ((adlf (* c-string)
418                      (alien-funcall (extern-alien
419                                      "alloc_directory_lispy_filenames"
420                                      (function (* c-string) c-string))
421                                     directory-name)))
422     (if (null-alien adlf)
423         (error 'simple-file-error
424                :pathname directory-name
425                :format-control "~@<couldn't read directory ~S: ~2I~_~A~:>"
426                :format-arguments (list directory-name (strerror)))
427         (unwind-protect
428             (c-strings->string-list adlf)
429           (alien-funcall (extern-alien "free_directory_lispy_filenames"
430                                        (function void (* c-string)))
431                          adlf)))))
432
433 (/show0 "filesys.lisp 498")
434
435 (defmacro !enumerate-matches ((var pathname &optional result
436                                    &key (verify-existence t)
437                                    (follow-links t))
438                               &body body)
439   `(block nil
440      (%enumerate-matches (pathname ,pathname)
441                          ,verify-existence
442                          ,follow-links
443                          (lambda (,var) ,@body))
444      ,result))
445
446 (/show0 "filesys.lisp 500")
447
448 ;;; Call FUNCTION on matches.
449 (defun %enumerate-matches (pathname verify-existence follow-links function)
450   (/noshow0 "entering %ENUMERATE-MATCHES")
451   (when (pathname-type pathname)
452     (unless (pathname-name pathname)
453       (error "cannot supply a type without a name:~%  ~S" pathname)))
454   (when (and (integerp (pathname-version pathname))
455              (member (pathname-type pathname) '(nil :unspecific)))
456     (error "cannot supply a version without a type:~%  ~S" pathname))
457   (let ((directory (pathname-directory pathname)))
458     (/noshow0 "computed DIRECTORY")
459     (if directory
460         (ecase (first directory)
461           (:absolute
462            (/noshow0 "absolute directory")
463            (%enumerate-directories "/" (rest directory) pathname
464                                    verify-existence follow-links
465                                    nil function))
466           (:relative
467            (/noshow0 "relative directory")
468            (%enumerate-directories "" (rest directory) pathname
469                                    verify-existence follow-links
470                                    nil function)))
471         (%enumerate-files "" pathname verify-existence function))))
472
473 ;;; Call FUNCTION on directories.
474 (defun %enumerate-directories (head tail pathname verify-existence
475                                follow-links nodes function)
476   (declare (simple-string head))
477   (macrolet ((unix-xstat (name)
478                `(if follow-links
479                     (sb!unix:unix-stat ,name)
480                     (sb!unix:unix-lstat ,name)))
481              (with-directory-node-noted ((head) &body body)
482                `(multiple-value-bind (res dev ino mode)
483                     (unix-xstat ,head)
484                   (when (and res (eql (logand mode sb!unix:s-ifmt)
485                                       sb!unix:s-ifdir))
486                     (let ((nodes (cons (cons dev ino) nodes)))
487                       ,@body))))
488              (with-directory-node-removed ((head) &body body)
489                `(multiple-value-bind (res dev ino mode)
490                     (unix-xstat ,head)
491                   (when (and res (eql (logand mode sb!unix:s-ifmt)
492                                       sb!unix:s-ifdir))
493                     (let ((nodes (remove (cons dev ino) nodes :test #'equal)))
494                       ,@body)))))
495     (if tail
496         (let ((piece (car tail)))
497           (etypecase piece
498             (simple-string
499              (let ((head (concatenate 'base-string head piece)))
500                (with-directory-node-noted (head)
501                  (%enumerate-directories (concatenate 'base-string head "/")
502                                          (cdr tail) pathname
503                                          verify-existence follow-links
504                                          nodes function))))
505             ((member :wild-inferiors)
506              ;; now with extra error case handling from CLHS
507              ;; 19.2.2.4.3 -- CSR, 2004-01-24
508              (when (member (cadr tail) '(:up :back))
509                (error 'simple-file-error
510                       :pathname pathname
511                       :format-control "~@<invalid use of ~S after :WILD-INFERIORS~@:>."
512                       :format-arguments (list (cadr tail))))
513              (%enumerate-directories head (rest tail) pathname
514                                      verify-existence follow-links
515                                      nodes function)
516              (dolist (name (ignore-errors (directory-lispy-filenames head)))
517                (let ((subdir (concatenate 'base-string head name)))
518                  (multiple-value-bind (res dev ino mode)
519                      (unix-xstat subdir)
520                    (declare (type (or fixnum null) mode))
521                    (when (and res (eql (logand mode sb!unix:s-ifmt)
522                                        sb!unix:s-ifdir))
523                      (unless (dolist (dir nodes nil)
524                                (when (and (eql (car dir) dev)
525                                           (eql (cdr dir) ino))
526                                  (return t)))
527                        (let ((nodes (cons (cons dev ino) nodes))
528                              (subdir (concatenate 'base-string subdir "/")))
529                          (%enumerate-directories subdir tail pathname
530                                                  verify-existence follow-links
531                                                  nodes function))))))))
532             ((or pattern (member :wild))
533              (dolist (name (directory-lispy-filenames head))
534                (when (or (eq piece :wild) (pattern-matches piece name))
535                  (let ((subdir (concatenate 'base-string head name)))
536                    (multiple-value-bind (res dev ino mode)
537                        (unix-xstat subdir)
538                      (declare (type (or fixnum null) mode))
539                      (when (and res
540                                 (eql (logand mode sb!unix:s-ifmt)
541                                      sb!unix:s-ifdir))
542                        (let ((nodes (cons (cons dev ino) nodes))
543                              (subdir (concatenate 'base-string subdir "/")))
544                          (%enumerate-directories subdir (rest tail) pathname
545                                                  verify-existence follow-links
546                                                  nodes function))))))))
547           ((member :up)
548            (when (string= head "/")
549              (error 'simple-file-error
550                     :pathname pathname
551                     :format-control "~@<invalid use of :UP after :ABSOLUTE.~@:>"))
552            (with-directory-node-removed (head)
553              (let ((head (concatenate 'base-string head "..")))
554                (with-directory-node-noted (head)
555                  (%enumerate-directories (concatenate 'base-string head "/")
556                                          (rest tail) pathname
557                                          verify-existence follow-links
558                                          nodes function)))))
559           ((member :back)
560            ;; :WILD-INFERIORS is handled above, so the only case here
561            ;; should be (:ABSOLUTE :BACK)
562            (aver (string= head "/"))
563            (error 'simple-file-error
564                   :pathname pathname
565                   :format-control "~@<invalid use of :BACK after :ABSOLUTE.~@:>"))))
566         (%enumerate-files head pathname verify-existence function))))
567
568 ;;; Call FUNCTION on files.
569 (defun %enumerate-files (directory pathname verify-existence function)
570   (declare (simple-string directory))
571   (/noshow0 "entering %ENUMERATE-FILES")
572   (let ((name (%pathname-name pathname))
573         (type (%pathname-type pathname))
574         (version (%pathname-version pathname)))
575     (/noshow0 "computed NAME, TYPE, and VERSION")
576     (cond ((member name '(nil :unspecific))
577            (/noshow0 "UNSPECIFIC, more or less")
578            (when (or (not verify-existence)
579                      (sb!unix:unix-file-kind directory))
580              (funcall function directory)))
581           ((or (pattern-p name)
582                (pattern-p type)
583                (eq name :wild)
584                (eq type :wild))
585            (/noshow0 "WILD, more or less")
586            ;; I IGNORE-ERRORS here just because the original CMU CL
587            ;; code did. I think the intent is that it's not an error
588            ;; to request matches to a wild pattern when no matches
589            ;; exist, but I haven't tried to figure out whether
590            ;; everything is kosher. (E.g. what if we try to match a
591            ;; wildcard but we don't have permission to read one of the
592            ;; relevant directories?) -- WHN 2001-04-17
593            (dolist (complete-filename (ignore-errors
594                                         (directory-lispy-filenames directory)))
595              (multiple-value-bind
596                  (file-name file-type file-version)
597                  (let ((*ignore-wildcards* t))
598                    (extract-name-type-and-version
599                     complete-filename 0 (length complete-filename)))
600                (when (and (components-match file-name name)
601                           (components-match file-type type)
602                           (components-match file-version version))
603                  (funcall function
604                           (concatenate 'base-string
605                                        directory
606                                        complete-filename))))))
607           (t
608            (/noshow0 "default case")
609            (let ((file (concatenate 'base-string directory name)))
610              (/noshow "computed basic FILE")
611              (unless (or (null type) (eq type :unspecific))
612                (/noshow0 "tweaking FILE for more-or-less-:UNSPECIFIC case")
613                (setf file (concatenate 'base-string file "." type)))
614              (unless (member version '(nil :newest :wild :unspecific))
615                (/noshow0 "tweaking FILE for more-or-less-:WILD case")
616                (setf file (concatenate 'base-string file "."
617                                        (quick-integer-to-string version))))
618              (/noshow0 "finished possibly tweaking FILE")
619              (when (or (not verify-existence)
620                        (sb!unix:unix-file-kind file t))
621                (/noshow0 "calling FUNCTION on FILE")
622                (funcall function file)))))))
623
624 (/noshow0 "filesys.lisp 603")
625
626 ;;; FIXME: Why do we need this?
627 (defun quick-integer-to-string (n)
628   (declare (type integer n))
629   (cond ((not (fixnump n))
630          (write-to-string n :base 10 :radix nil))
631         ((zerop n) "0")
632         ((eql n 1) "1")
633         ((minusp n)
634          (concatenate 'simple-base-string "-"
635                       (the simple-base-string (quick-integer-to-string (- n)))))
636         (t
637          (do* ((len (1+ (truncate (integer-length n) 3)))
638                (res (make-string len :element-type 'base-char))
639                (i (1- len) (1- i))
640                (q n)
641                (r 0))
642               ((zerop q)
643                (incf i)
644                (replace res res :start2 i :end2 len)
645                (shrink-vector res (- len i)))
646            (declare (simple-string res)
647                     (fixnum len i r q))
648            (multiple-value-setq (q r) (truncate q 10))
649            (setf (schar res i) (schar "0123456789" r))))))
650 \f
651 ;;;; UNIX-NAMESTRING
652
653 (defun empty-relative-pathname-spec-p (x)
654   (or (equal x "")
655       (and (pathnamep x)
656            (or (equal (pathname-directory x) '(:relative))
657                ;; KLUDGE: I'm not sure this second check should really
658                ;; have to be here. But on sbcl-0.6.12.7,
659                ;; (PATHNAME-DIRECTORY (PATHNAME "")) is NIL, and
660                ;; (PATHNAME "") seems to act like an empty relative
661                ;; pathname, so in order to work with that, I test
662                ;; for NIL here. -- WHN 2001-05-18
663                (null (pathname-directory x)))
664            (null (pathname-name x))
665            (null (pathname-type x)))
666       ;; (The ANSI definition of "pathname specifier" has 
667       ;; other cases, but none of them seem to admit the possibility
668       ;; of being empty and relative.)
669       ))
670
671 ;;; Convert PATHNAME into a string that can be used with UNIX system
672 ;;; calls, or return NIL if no match is found. Wild-cards are expanded.
673 (defun unix-namestring (pathname-spec &optional (for-input t))
674   (let* ((namestring (physicalize-pathname (merge-pathnames pathname-spec)))
675          (matches nil)) ; an accumulator for actual matches
676     (when (wild-pathname-p namestring)
677       (error 'simple-file-error
678              :pathname namestring
679              :format-control "bad place for a wild pathname"))
680     (!enumerate-matches (match namestring nil :verify-existence for-input)
681                         (push match matches))
682     (case (length matches)
683       (0 nil)
684       (1 (first matches))
685       (t (bug "!ENUMERATE-MATCHES returned more than one match on a non-wild pathname")))))
686 \f
687 ;;;; TRUENAME and PROBE-FILE
688
689 ;;; This is only trivially different from PROBE-FILE, which is silly
690 ;;; but ANSI.
691 (defun truename (pathname)
692   #!+sb-doc
693   "Return the pathname for the actual file described by PATHNAME.
694   An error of type FILE-ERROR is signalled if no such file exists,
695   or the pathname is wild.
696
697   Under Unix, the TRUENAME of a broken symlink is considered to be
698   the name of the broken symlink itself."
699   (let ((result (probe-file pathname)))
700     (unless result
701       (error 'simple-file-error
702              :pathname pathname
703              :format-control "The file ~S does not exist."
704              :format-arguments (list (namestring pathname))))
705     result))
706
707 (defun probe-file (pathname)
708   #!+sb-doc
709   "Return a pathname which is the truename of the file if it exists, or NIL
710   otherwise. An error of type FILE-ERROR is signaled if pathname is wild."
711   (let* ((defaulted-pathname (merge-pathnames
712                               pathname
713                               (sane-default-pathname-defaults)))
714          (namestring (unix-namestring defaulted-pathname t)))
715     (when (and namestring (sb!unix:unix-file-kind namestring t))
716       (let ((trueishname (sb!unix:unix-resolve-links namestring)))
717         (when trueishname
718           (let* ((*ignore-wildcards* t)
719                  (name (sb!unix:unix-simplify-pathname trueishname))) 
720             (if (eq (sb!unix:unix-file-kind name) :directory)
721                 (pathname (concatenate 'string name "/"))
722                 (pathname name))))))))
723 \f
724 ;;;; miscellaneous other operations
725
726 (/show0 "filesys.lisp 700")
727
728 (defun rename-file (file new-name)
729   #!+sb-doc
730   "Rename FILE to have the specified NEW-NAME. If FILE is a stream open to a
731   file, then the associated file is renamed."
732   (let* ((original (truename file))
733          (original-namestring (unix-namestring original t))
734          (new-name (merge-pathnames new-name original))
735          (new-namestring (unix-namestring new-name nil)))
736     (unless new-namestring
737       (error 'simple-file-error
738              :pathname new-name
739              :format-control "~S can't be created."
740              :format-arguments (list new-name)))
741     (multiple-value-bind (res error)
742         (sb!unix:unix-rename original-namestring new-namestring)
743       (unless res
744         (error 'simple-file-error
745                :pathname new-name
746                :format-control "~@<couldn't rename ~2I~_~A ~I~_to ~2I~_~A: ~
747                                 ~I~_~A~:>"
748                :format-arguments (list original new-name (strerror error))))
749       (when (streamp file)
750         (file-name file new-name))
751       (values new-name original (truename new-name)))))
752
753 (defun delete-file (file)
754   #!+sb-doc
755   "Delete the specified FILE."
756   (let ((namestring (unix-namestring file t)))
757     (when (streamp file)
758       (close file :abort t))
759     (unless namestring
760       (error 'simple-file-error
761              :pathname file
762              :format-control "~S doesn't exist."
763              :format-arguments (list file)))
764     (multiple-value-bind (res err) (sb!unix:unix-unlink namestring)
765       (unless res
766         (simple-file-perror "couldn't delete ~A" namestring err))))
767   t)
768 \f
769 ;;; (This is an ANSI Common Lisp function.) 
770 (defun user-homedir-pathname (&optional host)
771   "Return the home directory of the user as a pathname."
772   (declare (ignore host))
773   (pathname (sb!unix:uid-homedir (sb!unix:unix-getuid))))
774
775 (defun file-write-date (file)
776   #!+sb-doc
777   "Return file's creation date, or NIL if it doesn't exist.
778  An error of type file-error is signaled if file is a wild pathname"
779   (let ((name (unix-namestring file t)))
780     (when name
781       (multiple-value-bind
782             (res dev ino mode nlink uid gid rdev size atime mtime)
783           (sb!unix:unix-stat name)
784         (declare (ignore dev ino mode nlink uid gid rdev size atime))
785         (when res
786           (+ unix-to-universal-time mtime))))))
787
788 (defun file-author (file)
789   #!+sb-doc
790   "Return the file author as a string, or NIL if the author cannot be
791  determined. Signal an error of type FILE-ERROR if FILE doesn't exist,
792  or FILE is a wild pathname."
793   (let ((name (unix-namestring (pathname file) t)))
794     (unless name
795       (error 'simple-file-error
796              :pathname file
797              :format-control "~S doesn't exist."
798              :format-arguments (list file)))
799     (multiple-value-bind (winp dev ino mode nlink uid)
800         (sb!unix:unix-stat name)
801       (declare (ignore dev ino mode nlink))
802       (and winp (sb!unix:uid-username uid)))))
803 \f
804 ;;;; DIRECTORY
805
806 (/show0 "filesys.lisp 800")
807
808 (defun directory (pathname &key)
809   #!+sb-doc
810   "Return a list of PATHNAMEs, each the TRUENAME of a file that matched the
811    given pathname. Note that the interaction between this ANSI-specified
812    TRUENAMEing and the semantics of the Unix filesystem (symbolic links..)
813    means this function can sometimes return files which don't have the same
814    directory as PATHNAME."
815   (let (;; We create one entry in this hash table for each truename,
816         ;; as an asymptotically efficient way of removing duplicates
817         ;; (which can arise when e.g. multiple symlinks map to the
818         ;; same truename).
819         (truenames (make-hash-table :test #'equal))
820         (merged-pathname (merge-pathnames pathname)))
821     (!enumerate-matches (match merged-pathname)
822       (let* ((*ignore-wildcards* t)
823              ;; FIXME: Why not TRUENAME?  As reported by Milan Zamazal
824              ;; sbcl-devel 2003-10-05, using TRUENAME causes a race
825              ;; condition whereby removal of a file during the
826              ;; directory operation causes an error.  It's not clear
827              ;; what the right thing to do is, though.  -- CSR,
828              ;; 2003-10-13
829              (truename (probe-file match)))
830         (when truename
831           (setf (gethash (namestring truename) truenames)
832                 truename))))
833     (mapcar #'cdr
834             ;; Sorting isn't required by the ANSI spec, but sorting
835             ;; into some canonical order seems good just on the
836             ;; grounds that the implementation should have repeatable
837             ;; behavior when possible.
838             (sort (loop for name being each hash-key in truenames
839                         using (hash-value truename)
840                         collect (cons name truename))
841                   #'string<
842                   :key #'car))))
843 \f
844 (/show0 "filesys.lisp 899")
845
846 ;;; predicate to order pathnames by; goes by name
847 (defun pathname-order (x y)
848   (let ((xn (%pathname-name x))
849         (yn (%pathname-name y)))
850     (if (and xn yn)
851         (let ((res (string-lessp xn yn)))
852           (cond ((not res) nil)
853                 ((= res (length (the simple-string xn))) t)
854                 ((= res (length (the simple-string yn))) nil)
855                 (t t)))
856         xn)))
857 \f
858 (defun ensure-directories-exist (pathspec &key verbose (mode #o777))
859   #!+sb-doc
860   "Test whether the directories containing the specified file
861   actually exist, and attempt to create them if they do not.
862   The MODE argument is a CMUCL/SBCL-specific extension to control
863   the Unix permission bits."
864   (let ((pathname (physicalize-pathname (pathname pathspec)))
865         (created-p nil))
866     (when (wild-pathname-p pathname)
867       (error 'simple-file-error
868              :format-control "bad place for a wild pathname"
869              :pathname pathspec))
870     (let ((dir (pathname-directory pathname)))
871       (loop for i from 1 upto (length dir)
872             do (let ((newpath (make-pathname
873                                :host (pathname-host pathname)
874                                :device (pathname-device pathname)
875                                :directory (subseq dir 0 i))))
876                  (unless (probe-file newpath)
877                    (let ((namestring (namestring newpath)))
878                      (when verbose
879                        (format *standard-output*
880                                "~&creating directory: ~A~%"
881                                namestring))
882                      (sb!unix:unix-mkdir namestring mode)
883                      (unless (probe-file namestring)
884                        (error 'simple-file-error
885                               :pathname pathspec
886                               :format-control "can't create directory ~A"
887                               :format-arguments (list namestring)))
888                      (setf created-p t)))))
889       (values pathname created-p))))
890
891 (/show0 "filesys.lisp 1000")