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