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