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