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