0.8.13.77:
[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)
342                    (typep name 'string)
343                    (> (length name) 0)
344                    (position #\. name :start 1))
345           (error "too many dots in the name: ~S" pathname))
346         (when (and (typep name 'string)
347                    (string= name ""))
348           (error "name is of length 0: ~S" pathname))
349         (strings (unparse-unix-piece name)))
350       (when type-supplied
351         (unless name
352           (error "cannot specify the type without a file: ~S" pathname))
353         (when (typep type 'simple-base-string)
354           (when (position #\. type)
355             (error "type component can't have a #\. inside: ~S" pathname)))
356         (strings ".")
357         (strings (unparse-unix-piece type))))
358     (apply #'concatenate 'simple-string (strings))))
359
360 (/show0 "filesys.lisp 406")
361
362 (defun unparse-unix-namestring (pathname)
363   (declare (type pathname pathname))
364   (concatenate 'simple-string
365                (unparse-unix-directory pathname)
366                (unparse-unix-file pathname)))
367
368 (defun unparse-unix-enough (pathname defaults)
369   (declare (type pathname pathname defaults))
370   (flet ((lose ()
371            (error "~S cannot be represented relative to ~S."
372                   pathname defaults)))
373     (collect ((strings))
374       (let* ((pathname-directory (%pathname-directory pathname))
375              (defaults-directory (%pathname-directory defaults))
376              (prefix-len (length defaults-directory))
377              (result-directory
378               (cond ((null pathname-directory) '(:relative))
379                     ((eq (car pathname-directory) :relative)
380                      pathname-directory)
381                     ((and (> prefix-len 1)
382                           (>= (length pathname-directory) prefix-len)
383                           (compare-component (subseq pathname-directory
384                                                      0 prefix-len)
385                                              defaults-directory))
386                      ;; Pathname starts with a prefix of default. So
387                      ;; just use a relative directory from then on out.
388                      (cons :relative (nthcdr prefix-len pathname-directory)))
389                     ((eq (car pathname-directory) :absolute)
390                      ;; We are an absolute pathname, so we can just use it.
391                      pathname-directory)
392                     (t
393                      (bug "Bad fallthrough in ~S" 'unparse-unix-enough)))))
394         (strings (unparse-unix-directory-list result-directory)))
395       (let* ((pathname-type (%pathname-type pathname))
396              (type-needed (and pathname-type
397                                (not (eq pathname-type :unspecific))))
398              (pathname-name (%pathname-name pathname))
399              (name-needed (or type-needed
400                               (and pathname-name
401                                    (not (compare-component pathname-name
402                                                            (%pathname-name
403                                                             defaults)))))))
404         (when name-needed
405           (unless pathname-name (lose))
406           (when (and (null pathname-type)
407                      (position #\. pathname-name :start 1))
408             (error "too many dots in the name: ~S" pathname))
409           (strings (unparse-unix-piece pathname-name)))
410         (when type-needed
411           (when (or (null pathname-type) (eq pathname-type :unspecific))
412             (lose))
413           (when (typep pathname-type 'simple-base-string)
414             (when (position #\. pathname-type)
415               (error "type component can't have a #\. inside: ~S" pathname)))
416           (strings ".")
417           (strings (unparse-unix-piece pathname-type))))
418       (apply #'concatenate 'simple-string (strings)))))
419 \f
420 ;;;; wildcard matching stuff
421
422 ;;; Return a list of all the Lispy filenames (not including e.g. the
423 ;;; Unix magic "." and "..") in the directory named by DIRECTORY-NAME.
424 (defun directory-lispy-filenames (directory-name)
425   (with-alien ((adlf (* c-string)
426                      (alien-funcall (extern-alien
427                                      "alloc_directory_lispy_filenames"
428                                      (function (* c-string) c-string))
429                                     directory-name)))
430     (if (null-alien adlf)
431         (error 'simple-file-error
432                :pathname directory-name
433                :format-control "~@<couldn't read directory ~S: ~2I~_~A~:>"
434                :format-arguments (list directory-name (strerror)))
435         (unwind-protect
436             (c-strings->string-list adlf)
437           (alien-funcall (extern-alien "free_directory_lispy_filenames"
438                                        (function void (* c-string)))
439                          adlf)))))
440
441 (/show0 "filesys.lisp 498")
442
443 (defmacro !enumerate-matches ((var pathname &optional result
444                                    &key (verify-existence t)
445                                    (follow-links t))
446                               &body body)
447   `(block nil
448      (%enumerate-matches (pathname ,pathname)
449                          ,verify-existence
450                          ,follow-links
451                          (lambda (,var) ,@body))
452      ,result))
453
454 (/show0 "filesys.lisp 500")
455
456 ;;; Call FUNCTION on matches.
457 (defun %enumerate-matches (pathname verify-existence follow-links function)
458   (/noshow0 "entering %ENUMERATE-MATCHES")
459   (when (pathname-type pathname)
460     (unless (pathname-name pathname)
461       (error "cannot supply a type without a name:~%  ~S" pathname)))
462   (when (and (integerp (pathname-version pathname))
463              (member (pathname-type pathname) '(nil :unspecific)))
464     (error "cannot supply a version without a type:~%  ~S" pathname))
465   (let ((directory (pathname-directory pathname)))
466     (/noshow0 "computed DIRECTORY")
467     (if directory
468         (ecase (first directory)
469           (:absolute
470            (/noshow0 "absolute directory")
471            (%enumerate-directories "/" (rest directory) pathname
472                                    verify-existence follow-links
473                                    nil function))
474           (:relative
475            (/noshow0 "relative directory")
476            (%enumerate-directories "" (rest directory) pathname
477                                    verify-existence follow-links
478                                    nil function)))
479         (%enumerate-files "" pathname verify-existence function))))
480
481 ;;; Call FUNCTION on directories.
482 (defun %enumerate-directories (head tail pathname verify-existence
483                                follow-links nodes function)
484   (declare (simple-string head))
485   (macrolet ((unix-xstat (name)
486                `(if follow-links
487                     (sb!unix:unix-stat ,name)
488                     (sb!unix:unix-lstat ,name)))
489              (with-directory-node-noted ((head) &body body)
490                `(multiple-value-bind (res dev ino mode)
491                     (unix-xstat ,head)
492                   (when (and res (eql (logand mode sb!unix:s-ifmt)
493                                       sb!unix:s-ifdir))
494                     (let ((nodes (cons (cons dev ino) nodes)))
495                       ,@body))))
496              (with-directory-node-removed ((head) &body body)
497                `(multiple-value-bind (res dev ino mode)
498                     (unix-xstat ,head)
499                   (when (and res (eql (logand mode sb!unix:s-ifmt)
500                                       sb!unix:s-ifdir))
501                     (let ((nodes (remove (cons dev ino) nodes :test #'equal)))
502                       ,@body)))))
503     (if tail
504         (let ((piece (car tail)))
505           (etypecase piece
506             (simple-string
507              (let ((head (concatenate 'base-string head piece)))
508                (with-directory-node-noted (head)
509                  (%enumerate-directories (concatenate 'base-string head "/")
510                                          (cdr tail) pathname
511                                          verify-existence follow-links
512                                          nodes function))))
513             ((member :wild-inferiors)
514              ;; now with extra error case handling from CLHS
515              ;; 19.2.2.4.3 -- CSR, 2004-01-24
516              (when (member (cadr tail) '(:up :back))
517                (error 'simple-file-error
518                       :pathname pathname
519                       :format-control "~@<invalid use of ~S after :WILD-INFERIORS~@:>."
520                       :format-arguments (list (cadr tail))))
521              (%enumerate-directories head (rest tail) pathname
522                                      verify-existence follow-links
523                                      nodes function)
524              (dolist (name (ignore-errors (directory-lispy-filenames head)))
525                (let ((subdir (concatenate 'base-string head name)))
526                  (multiple-value-bind (res dev ino mode)
527                      (unix-xstat subdir)
528                    (declare (type (or fixnum null) mode))
529                    (when (and res (eql (logand mode sb!unix:s-ifmt)
530                                        sb!unix:s-ifdir))
531                      (unless (dolist (dir nodes nil)
532                                (when (and (eql (car dir) dev)
533                                           (eql (cdr dir) ino))
534                                  (return t)))
535                        (let ((nodes (cons (cons dev ino) nodes))
536                              (subdir (concatenate 'base-string subdir "/")))
537                          (%enumerate-directories subdir tail pathname
538                                                  verify-existence follow-links
539                                                  nodes function))))))))
540             ((or pattern (member :wild))
541              (dolist (name (directory-lispy-filenames head))
542                (when (or (eq piece :wild) (pattern-matches piece name))
543                  (let ((subdir (concatenate 'base-string head name)))
544                    (multiple-value-bind (res dev ino mode)
545                        (unix-xstat subdir)
546                      (declare (type (or fixnum null) mode))
547                      (when (and res
548                                 (eql (logand mode sb!unix:s-ifmt)
549                                      sb!unix:s-ifdir))
550                        (let ((nodes (cons (cons dev ino) nodes))
551                              (subdir (concatenate 'base-string subdir "/")))
552                          (%enumerate-directories subdir (rest tail) pathname
553                                                  verify-existence follow-links
554                                                  nodes function))))))))
555           ((member :up)
556            (when (string= head "/")
557              (error 'simple-file-error
558                     :pathname pathname
559                     :format-control "~@<invalid use of :UP after :ABSOLUTE.~@:>"))
560            (with-directory-node-removed (head)
561              (let ((head (concatenate 'base-string head "..")))
562                (with-directory-node-noted (head)
563                  (%enumerate-directories (concatenate 'base-string head "/")
564                                          (rest tail) pathname
565                                          verify-existence follow-links
566                                          nodes function)))))
567           ((member :back)
568            ;; :WILD-INFERIORS is handled above, so the only case here
569            ;; should be (:ABSOLUTE :BACK)
570            (aver (string= head "/"))
571            (error 'simple-file-error
572                   :pathname pathname
573                   :format-control "~@<invalid use of :BACK after :ABSOLUTE.~@:>"))))
574         (%enumerate-files head pathname verify-existence function))))
575
576 ;;; Call FUNCTION on files.
577 (defun %enumerate-files (directory pathname verify-existence function)
578   (declare (simple-string directory))
579   (/noshow0 "entering %ENUMERATE-FILES")
580   (let ((name (%pathname-name pathname))
581         (type (%pathname-type pathname))
582         (version (%pathname-version pathname)))
583     (/noshow0 "computed NAME, TYPE, and VERSION")
584     (cond ((member name '(nil :unspecific))
585            (/noshow0 "UNSPECIFIC, more or less")
586            (when (or (not verify-existence)
587                      (sb!unix:unix-file-kind directory))
588              (funcall function directory)))
589           ((or (pattern-p name)
590                (pattern-p type)
591                (eq name :wild)
592                (eq type :wild))
593            (/noshow0 "WILD, more or less")
594            ;; I IGNORE-ERRORS here just because the original CMU CL
595            ;; code did. I think the intent is that it's not an error
596            ;; to request matches to a wild pattern when no matches
597            ;; exist, but I haven't tried to figure out whether
598            ;; everything is kosher. (E.g. what if we try to match a
599            ;; wildcard but we don't have permission to read one of the
600            ;; relevant directories?) -- WHN 2001-04-17
601            (dolist (complete-filename (ignore-errors
602                                         (directory-lispy-filenames directory)))
603              (multiple-value-bind
604                  (file-name file-type file-version)
605                  (let ((*ignore-wildcards* t))
606                    (extract-name-type-and-version
607                     complete-filename 0 (length complete-filename)))
608                (when (and (components-match file-name name)
609                           (components-match file-type type)
610                           (components-match file-version version))
611                  (funcall function
612                           (concatenate 'base-string
613                                        directory
614                                        complete-filename))))))
615           (t
616            (/noshow0 "default case")
617            (let ((file (concatenate 'base-string directory name)))
618              (/noshow "computed basic FILE")
619              (unless (or (null type) (eq type :unspecific))
620                (/noshow0 "tweaking FILE for more-or-less-:UNSPECIFIC case")
621                (setf file (concatenate 'base-string file "." type)))
622              (unless (member version '(nil :newest :wild :unspecific))
623                (/noshow0 "tweaking FILE for more-or-less-:WILD case")
624                (setf file (concatenate 'base-string file "."
625                                        (quick-integer-to-string version))))
626              (/noshow0 "finished possibly tweaking FILE")
627              (when (or (not verify-existence)
628                        (sb!unix:unix-file-kind file t))
629                (/noshow0 "calling FUNCTION on FILE")
630                (funcall function file)))))))
631
632 (/noshow0 "filesys.lisp 603")
633
634 ;;; FIXME: Why do we need this?
635 (defun quick-integer-to-string (n)
636   (declare (type integer n))
637   (cond ((not (fixnump n))
638          (write-to-string n :base 10 :radix nil))
639         ((zerop n) "0")
640         ((eql n 1) "1")
641         ((minusp n)
642          (concatenate 'simple-base-string "-"
643                       (the simple-base-string (quick-integer-to-string (- n)))))
644         (t
645          (do* ((len (1+ (truncate (integer-length n) 3)))
646                (res (make-string len :element-type 'base-char))
647                (i (1- len) (1- i))
648                (q n)
649                (r 0))
650               ((zerop q)
651                (incf i)
652                (replace res res :start2 i :end2 len)
653                (shrink-vector res (- len i)))
654            (declare (simple-string res)
655                     (fixnum len i r q))
656            (multiple-value-setq (q r) (truncate q 10))
657            (setf (schar res i) (schar "0123456789" r))))))
658 \f
659 ;;;; UNIX-NAMESTRING
660
661 (defun empty-relative-pathname-spec-p (x)
662   (or (equal x "")
663       (and (pathnamep x)
664            (or (equal (pathname-directory x) '(:relative))
665                ;; KLUDGE: I'm not sure this second check should really
666                ;; have to be here. But on sbcl-0.6.12.7,
667                ;; (PATHNAME-DIRECTORY (PATHNAME "")) is NIL, and
668                ;; (PATHNAME "") seems to act like an empty relative
669                ;; pathname, so in order to work with that, I test
670                ;; for NIL here. -- WHN 2001-05-18
671                (null (pathname-directory x)))
672            (null (pathname-name x))
673            (null (pathname-type x)))
674       ;; (The ANSI definition of "pathname specifier" has 
675       ;; other cases, but none of them seem to admit the possibility
676       ;; of being empty and relative.)
677       ))
678
679 ;;; Convert PATHNAME into a string that can be used with UNIX system
680 ;;; calls, or return NIL if no match is found. Wild-cards are expanded.
681 (defun unix-namestring (pathname-spec &optional (for-input t))
682   (let* ((namestring (physicalize-pathname (merge-pathnames pathname-spec)))
683          (matches nil)) ; an accumulator for actual matches
684     (when (wild-pathname-p namestring)
685       (error 'simple-file-error
686              :pathname namestring
687              :format-control "bad place for a wild pathname"))
688     (!enumerate-matches (match namestring nil :verify-existence for-input)
689                         (push match matches))
690     (case (length matches)
691       (0 nil)
692       (1 (first matches))
693       (t (bug "!ENUMERATE-MATCHES returned more than one match on a non-wild pathname")))))
694 \f
695 ;;;; TRUENAME and PROBE-FILE
696
697 ;;; This is only trivially different from PROBE-FILE, which is silly
698 ;;; but ANSI.
699 (defun truename (pathname)
700   #!+sb-doc
701   "Return the pathname for the actual file described by PATHNAME.
702   An error of type FILE-ERROR is signalled if no such file exists,
703   or the pathname is wild.
704
705   Under Unix, the TRUENAME of a broken symlink is considered to be
706   the name of the broken symlink itself."
707   (let ((result (probe-file pathname)))
708     (unless result
709       (error 'simple-file-error
710              :pathname pathname
711              :format-control "The file ~S does not exist."
712              :format-arguments (list (namestring pathname))))
713     result))
714
715 (defun probe-file (pathname)
716   #!+sb-doc
717   "Return a pathname which is the truename of the file if it exists, or NIL
718   otherwise. An error of type FILE-ERROR is signaled if pathname is wild."
719   (let* ((defaulted-pathname (merge-pathnames
720                               pathname
721                               (sane-default-pathname-defaults)))
722          (namestring (unix-namestring defaulted-pathname t)))
723     (when (and namestring (sb!unix:unix-file-kind namestring t))
724       (let ((trueishname (sb!unix:unix-resolve-links namestring)))
725         (when trueishname
726           (let* ((*ignore-wildcards* t)
727                  (name (sb!unix:unix-simplify-pathname trueishname))) 
728             (if (eq (sb!unix:unix-file-kind name) :directory)
729                 (pathname (concatenate 'string name "/"))
730                 (pathname name))))))))
731 \f
732 ;;;; miscellaneous other operations
733
734 (/show0 "filesys.lisp 700")
735
736 (defun rename-file (file new-name)
737   #!+sb-doc
738   "Rename FILE to have the specified NEW-NAME. If FILE is a stream open to a
739   file, then the associated file is renamed."
740   (let* ((original (truename file))
741          (original-namestring (unix-namestring original t))
742          (new-name (merge-pathnames new-name original))
743          (new-namestring (unix-namestring new-name nil)))
744     (unless new-namestring
745       (error 'simple-file-error
746              :pathname new-name
747              :format-control "~S can't be created."
748              :format-arguments (list new-name)))
749     (multiple-value-bind (res error)
750         (sb!unix:unix-rename original-namestring new-namestring)
751       (unless res
752         (error 'simple-file-error
753                :pathname new-name
754                :format-control "~@<couldn't rename ~2I~_~A ~I~_to ~2I~_~A: ~
755                                 ~I~_~A~:>"
756                :format-arguments (list original new-name (strerror error))))
757       (when (streamp file)
758         (file-name file new-name))
759       (values new-name original (truename new-name)))))
760
761 (defun delete-file (file)
762   #!+sb-doc
763   "Delete the specified FILE."
764   (let ((namestring (unix-namestring file t)))
765     (when (streamp file)
766       (close file :abort t))
767     (unless namestring
768       (error 'simple-file-error
769              :pathname file
770              :format-control "~S doesn't exist."
771              :format-arguments (list file)))
772     (multiple-value-bind (res err) (sb!unix:unix-unlink namestring)
773       (unless res
774         (simple-file-perror "couldn't delete ~A" namestring err))))
775   t)
776 \f
777 ;;; (This is an ANSI Common Lisp function.) 
778 (defun user-homedir-pathname (&optional host)
779   "Return the home directory of the user as a pathname."
780   (declare (ignore host))
781   (pathname (sb!unix:uid-homedir (sb!unix:unix-getuid))))
782
783 (defun file-write-date (file)
784   #!+sb-doc
785   "Return file's creation date, or NIL if it doesn't exist.
786  An error of type file-error is signaled if file is a wild pathname"
787   (let ((name (unix-namestring file t)))
788     (when name
789       (multiple-value-bind
790             (res dev ino mode nlink uid gid rdev size atime mtime)
791           (sb!unix:unix-stat name)
792         (declare (ignore dev ino mode nlink uid gid rdev size atime))
793         (when res
794           (+ unix-to-universal-time mtime))))))
795
796 (defun file-author (file)
797   #!+sb-doc
798   "Return the file author as a string, or NIL if the author cannot be
799  determined. Signal an error of type FILE-ERROR if FILE doesn't exist,
800  or FILE is a wild pathname."
801   (let ((name (unix-namestring (pathname file) t)))
802     (unless name
803       (error 'simple-file-error
804              :pathname file
805              :format-control "~S doesn't exist."
806              :format-arguments (list file)))
807     (multiple-value-bind (winp dev ino mode nlink uid)
808         (sb!unix:unix-stat name)
809       (declare (ignore dev ino mode nlink))
810       (and winp (sb!unix:uid-username uid)))))
811 \f
812 ;;;; DIRECTORY
813
814 (/show0 "filesys.lisp 800")
815
816 ;;; NOTE: There is a fair amount of hair below that is probably not
817 ;;; strictly necessary.
818 ;;;
819 ;;; The issue is the following: what does (DIRECTORY "SYS:*;") mean?
820 ;;; Until 2004-01, SBCL's behaviour was unquestionably wrong, as it
821 ;;; did not translate the logical pathname at all, but instead treated
822 ;;; it as a physical one.  Other Lisps seem to to treat this call as
823 ;;; equivalent to (DIRECTORY (TRANSLATE-LOGICAL-PATHNAME "SYS:*;")),
824 ;;; which is fine as far as it goes, but not very interesting, and
825 ;;; arguably counterintuitive.  (PATHNAME-MATCH-P "SYS:SRC;" "SYS:*;")
826 ;;; is true, so why should "SYS:SRC;" not show up in the call to
827 ;;; DIRECTORY?  (assuming the physical pathname corresponding to it
828 ;;; exists, of course).
829 ;;;
830 ;;; So, the interpretation that I am pushing is for all pathnames
831 ;;; matching the input pathname to be queried.  This means that we
832 ;;; need to compute the intersection of the input pathname and the
833 ;;; logical host FROM translations, and then translate the resulting
834 ;;; pathname using the host to the TO translation; this treatment is
835 ;;; recursively invoked until we get a physical pathname, whereupon
836 ;;; our physical DIRECTORY implementation takes over.
837
838 ;;; FIXME: this is an incomplete implementation.  It only works when
839 ;;; both are logical pathnames (which is OK, because that's the only
840 ;;; case when we call it), but there are other pitfalls as well: see
841 ;;; the DIRECTORY-HELPER below for some, but others include a lack of
842 ;;; pattern handling.
843 (defun pathname-intersections (one two)
844   (aver (logical-pathname-p one))
845   (aver (logical-pathname-p two))
846   (labels
847       ((intersect-version (one two)
848          (aver (typep one '(or null (member :newest :wild :unspecific)
849                             integer)))
850          (aver (typep two '(or null (member :newest :wild :unspecific)
851                             integer)))
852          (cond
853            ((eq one :wild) two)
854            ((eq two :wild) one)
855            ((or (null one) (eq one :unspecific)) two)
856            ((or (null two) (eq two :unspecific)) one)
857            ((eql one two) one)
858            (t nil)))
859        (intersect-name/type (one two)
860          (aver (typep one '(or null (member :wild :unspecific) string)))
861          (aver (typep two '(or null (member :wild :unspecific) string)))
862          (cond
863            ((eq one :wild) two)
864            ((eq two :wild) one)
865            ((or (null one) (eq one :unspecific)) two)
866            ((or (null two) (eq two :unspecific)) one)
867            ((string= one two) one)
868            (t nil)))
869        (intersect-directory (one two)
870          (aver (typep one '(or null (member :wild :unspecific) list)))
871          (aver (typep two '(or null (member :wild :unspecific) list)))
872          (cond
873            ((eq one :wild) two)
874            ((eq two :wild) one)
875            ((or (null one) (eq one :unspecific)) two)
876            ((or (null two) (eq two :unspecific)) one)
877            (t (aver (eq (car one) (car two)))
878               (mapcar
879                (lambda (x) (cons (car one) x))
880                (intersect-directory-helper (cdr one) (cdr two)))))))
881     (let ((version (intersect-version
882                     (pathname-version one) (pathname-version two)))
883           (name (intersect-name/type
884                  (pathname-name one) (pathname-name two)))
885           (type (intersect-name/type
886                  (pathname-type one) (pathname-type two)))
887           (host (pathname-host one)))
888       (mapcar (lambda (d)
889                 (make-pathname :host host :name name :type type
890                                :version version :directory d))
891               (intersect-directory
892                (pathname-directory one) (pathname-directory two))))))
893
894 ;;; FIXME: written as its own function because I (CSR) don't
895 ;;; understand it, so helping both debuggability and modularity.  In
896 ;;; case anyone is motivated to rewrite it, it returns a list of
897 ;;; sublists representing the intersection of the two input directory
898 ;;; paths (excluding the initial :ABSOLUTE or :RELATIVE).
899 ;;;
900 ;;; FIXME: Does not work with :UP or :BACK
901 ;;; FIXME: Does not work with patterns
902 ;;;
903 ;;; FIXME: PFD suggests replacing this implementation with a DFA
904 ;;; conversion of a NDFA.  Find out (a) what this means and (b) if it
905 ;;; turns out to be worth it.
906 (defun intersect-directory-helper (one two)
907   (flet ((simple-intersection (cone ctwo)
908            (cond
909              ((eq cone :wild) ctwo)
910              ((eq ctwo :wild) cone)
911              (t (aver (typep cone 'string))
912                 (aver (typep ctwo 'string))
913                 (if (string= cone ctwo) cone nil)))))
914     (macrolet
915         ((loop-possible-wild-inferiors-matches
916              (lower-bound bounding-sequence order)
917            (let ((index (gensym)) (g2 (gensym)) (g3 (gensym)) (l (gensym)))
918              `(let ((,l (length ,bounding-sequence)))
919                (loop for ,index from ,lower-bound to ,l
920                 append (mapcar (lambda (,g2)
921                                  (append
922                                   (butlast ,bounding-sequence (- ,l ,index))
923                                   ,g2))
924                         (mapcar
925                          (lambda (,g3)
926                            (append
927                             (if (eq (car (nthcdr ,index ,bounding-sequence))
928                                     :wild-inferiors)
929                                 '(:wild-inferiors)
930                                 nil) ,g3))
931                          (intersect-directory-helper
932                           ,@(if order
933                                 `((nthcdr ,index one) (cdr two))
934                                 `((cdr one) (nthcdr ,index two)))))))))))
935       (cond
936         ((and (eq (car one) :wild-inferiors)
937               (eq (car two) :wild-inferiors))
938          (delete-duplicates
939           (append (mapcar (lambda (x) (cons :wild-inferiors x))
940                           (intersect-directory-helper (cdr one) (cdr two)))
941                   (loop-possible-wild-inferiors-matches 2 one t)
942                   (loop-possible-wild-inferiors-matches 2 two nil))
943           :test 'equal))
944         ((eq (car one) :wild-inferiors)
945          (delete-duplicates (loop-possible-wild-inferiors-matches 0 two nil)
946                             :test 'equal))
947         ((eq (car two) :wild-inferiors)
948          (delete-duplicates (loop-possible-wild-inferiors-matches 0 one t)
949                             :test 'equal))
950         ((and (null one) (null two)) (list nil))
951         ((null one) nil)
952         ((null two) nil)
953         (t (and (simple-intersection (car one) (car two))
954                 (mapcar (lambda (x) (cons (simple-intersection
955                                            (car one) (car two)) x))
956                         (intersect-directory-helper (cdr one) (cdr two)))))))))
957
958 (defun directory (pathname &key)
959   #!+sb-doc
960   "Return a list of PATHNAMEs, each the TRUENAME of a file that matched the
961    given pathname. Note that the interaction between this ANSI-specified
962    TRUENAMEing and the semantics of the Unix filesystem (symbolic links..)
963    means this function can sometimes return files which don't have the same
964    directory as PATHNAME."
965   (let (;; We create one entry in this hash table for each truename,
966         ;; as an asymptotically efficient way of removing duplicates
967         ;; (which can arise when e.g. multiple symlinks map to the
968         ;; same truename).
969         (truenames (make-hash-table :test #'equal))
970         ;; FIXME: Possibly this MERGE-PATHNAMES call should only
971         ;; happen once we get a physical pathname.
972         (merged-pathname (merge-pathnames pathname)))
973     (labels ((do-physical-directory (pathname)
974                (aver (not (logical-pathname-p pathname)))
975                (!enumerate-matches (match pathname)
976                  (let* ((*ignore-wildcards* t)
977                         ;; FIXME: Why not TRUENAME?  As reported by
978                         ;; Milan Zamazal sbcl-devel 2003-10-05, using
979                         ;; TRUENAME causes a race condition whereby
980                         ;; removal of a file during the directory
981                         ;; operation causes an error.  It's not clear
982                         ;; what the right thing to do is, though.  --
983                         ;; CSR, 2003-10-13
984                         (truename (probe-file match)))
985                    (when truename
986                      (setf (gethash (namestring truename) truenames)
987                            truename)))))
988              (do-directory (pathname)
989                (if (logical-pathname-p pathname)
990                    (let ((host (intern-logical-host (pathname-host pathname))))
991                      (dolist (x (logical-host-canon-transls host))
992                        (destructuring-bind (from to) x
993                          (let ((intersections
994                                 (pathname-intersections pathname from)))
995                            (dolist (p intersections)
996                              (do-directory (translate-pathname p from to)))))))
997                    (do-physical-directory pathname))))
998       (do-directory merged-pathname))
999     (mapcar #'cdr
1000             ;; Sorting isn't required by the ANSI spec, but sorting
1001             ;; into some canonical order seems good just on the
1002             ;; grounds that the implementation should have repeatable
1003             ;; behavior when possible.
1004             (sort (loop for name being each hash-key in truenames
1005                         using (hash-value truename)
1006                         collect (cons name truename))
1007                   #'string<
1008                   :key #'car))))
1009 \f
1010 (/show0 "filesys.lisp 899")
1011
1012 ;;; predicate to order pathnames by; goes by name
1013 (defun pathname-order (x y)
1014   (let ((xn (%pathname-name x))
1015         (yn (%pathname-name y)))
1016     (if (and xn yn)
1017         (let ((res (string-lessp xn yn)))
1018           (cond ((not res) nil)
1019                 ((= res (length (the simple-string xn))) t)
1020                 ((= res (length (the simple-string yn))) nil)
1021                 (t t)))
1022         xn)))
1023 \f
1024 (defun ensure-directories-exist (pathspec &key verbose (mode #o777))
1025   #!+sb-doc
1026   "Test whether the directories containing the specified file
1027   actually exist, and attempt to create them if they do not.
1028   The MODE argument is a CMUCL/SBCL-specific extension to control
1029   the Unix permission bits."
1030   (let ((pathname (physicalize-pathname (pathname pathspec)))
1031         (created-p nil))
1032     (when (wild-pathname-p pathname)
1033       (error 'simple-file-error
1034              :format-control "bad place for a wild pathname"
1035              :pathname pathspec))
1036     (let ((dir (pathname-directory pathname)))
1037       (loop for i from 1 upto (length dir)
1038             do (let ((newpath (make-pathname
1039                                :host (pathname-host pathname)
1040                                :device (pathname-device pathname)
1041                                :directory (subseq dir 0 i))))
1042                  (unless (probe-file newpath)
1043                    (let ((namestring (namestring newpath)))
1044                      (when verbose
1045                        (format *standard-output*
1046                                "~&creating directory: ~A~%"
1047                                namestring))
1048                      (sb!unix:unix-mkdir namestring mode)
1049                      (unless (probe-file namestring)
1050                        (error 'simple-file-error
1051                               :pathname pathspec
1052                               :format-control "can't create directory ~A"
1053                               :format-arguments (list namestring)))
1054                      (setf created-p t)))))
1055       (values pathname created-p))))
1056
1057 (/show0 "filesys.lisp 1000")