0.pre7.119:
[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)))
58          (dst 0)
59          (quoted nil))
60     (do ((src start (1+ src)))
61         ((= src end))
62       (cond (quoted
63              (setf (schar result dst) (schar namestr src))
64              (setf quoted nil)
65              (incf dst))
66             (t
67              (let ((char (schar namestr src)))
68                (cond ((char= char #\\)
69                       (setq quoted t))
70                      (t
71                       (setf (schar result dst) char)
72                       (incf dst)))))))
73     (when quoted
74       (error 'namestring-parse-error
75              :complaint "backslash in a bad place"
76              :namestring namestr
77              :offset (1- end)))
78     (shrink-vector result dst)))
79
80 (defvar *ignore-wildcards* nil)
81
82 (/show0 "filesys.lisp 86")
83
84 (defun maybe-make-pattern (namestr start end)
85   (declare (type simple-base-string namestr)
86            (type index start end))
87   (if *ignore-wildcards*
88       (subseq namestr start end)
89       (collect ((pattern))
90         (let ((quoted nil)
91               (any-quotes nil)
92               (last-regular-char nil)
93               (index start))
94           (flet ((flush-pending-regulars ()
95                    (when last-regular-char
96                      (pattern (if any-quotes
97                                   (remove-backslashes namestr
98                                                       last-regular-char
99                                                       index)
100                                   (subseq namestr last-regular-char index)))
101                      (setf any-quotes nil)
102                      (setf last-regular-char nil))))
103             (loop
104               (when (>= index end)
105                 (return))
106               (let ((char (schar namestr index)))
107                 (cond (quoted
108                        (incf index)
109                        (setf quoted nil))
110                       ((char= char #\\)
111                        (setf quoted t)
112                        (setf any-quotes t)
113                        (unless last-regular-char
114                          (setf last-regular-char index))
115                        (incf index))
116                       ((char= char #\?)
117                        (flush-pending-regulars)
118                        (pattern :single-char-wild)
119                        (incf index))
120                       ((char= char #\*)
121                        (flush-pending-regulars)
122                        (pattern :multi-char-wild)
123                        (incf index))
124                       ((char= char #\[)
125                        (flush-pending-regulars)
126                        (let ((close-bracket
127                               (position #\] namestr :start index :end end)))
128                          (unless close-bracket
129                            (error 'namestring-parse-error
130                                   :complaint "#\\[ with no corresponding #\\]"
131                                   :namestring namestr
132                                   :offset index))
133                          (pattern (list :character-set
134                                         (subseq namestr
135                                                 (1+ index)
136                                                 close-bracket)))
137                          (setf index (1+ close-bracket))))
138                       (t
139                        (unless last-regular-char
140                          (setf last-regular-char index))
141                        (incf index)))))
142             (flush-pending-regulars)))
143         (cond ((null (pattern))
144                "")
145               ((null (cdr (pattern)))
146                (let ((piece (first (pattern))))
147                  (typecase piece
148                    ((member :multi-char-wild) :wild)
149                    (simple-string piece)
150                    (t
151                     (make-pattern (pattern))))))
152               (t
153                (make-pattern (pattern)))))))
154
155 (/show0 "filesys.lisp 160")
156
157 (defun extract-name-type-and-version (namestr start end)
158   (declare (type simple-base-string namestr)
159            (type index start end))
160   (let* ((last-dot (position #\. namestr :start (1+ start) :end end
161                              :from-end t))
162          (second-to-last-dot (and last-dot
163                                   (position #\. namestr :start (1+ start)
164                                             :end last-dot :from-end t)))
165          (version :newest))
166     ;; If there is a second-to-last dot, check to see whether there is
167     ;; a valid version after the last dot.
168     (when second-to-last-dot
169       (cond ((and (= (+ last-dot 2) end)
170                   (char= (schar namestr (1+ last-dot)) #\*))
171              (setf version :wild))
172             ((and (< (1+ last-dot) end)
173                   (do ((index (1+ last-dot) (1+ index)))
174                       ((= index end) t)
175                     (unless (char<= #\0 (schar namestr index) #\9)
176                       (return nil))))
177              (setf version
178                    (parse-integer namestr :start (1+ last-dot) :end end)))
179             (t
180              (setf second-to-last-dot nil))))
181     (cond (second-to-last-dot
182            (values (maybe-make-pattern namestr start second-to-last-dot)
183                    (maybe-make-pattern namestr
184                                        (1+ second-to-last-dot)
185                                        last-dot)
186                    version))
187           (last-dot
188            (values (maybe-make-pattern namestr start last-dot)
189                    (maybe-make-pattern namestr (1+ last-dot) end)
190                    version))
191           (t
192            (values (maybe-make-pattern namestr start end)
193                    nil
194                    version)))))
195
196 (/show0 "filesys.lisp 200")
197
198 ;;; Take a string and return a list of cons cells that mark the char
199 ;;; separated subseq. The first value is true if absolute directories
200 ;;; location.
201 (defun split-at-slashes (namestr start end)
202   (declare (type simple-base-string namestr)
203            (type index start end))
204   (let ((absolute (and (/= start end)
205                        (char= (schar namestr start) #\/))))
206     (when absolute
207       (incf start))
208     ;; Next, split the remainder into slash-separated chunks.
209     (collect ((pieces))
210       (loop
211         (let ((slash (position #\/ namestr :start start :end end)))
212           (pieces (cons start (or slash end)))
213           (unless slash
214             (return))
215           (setf start (1+ slash))))
216       (values absolute (pieces)))))
217
218 ;;; the thing before a colon in a logical path
219 (def!struct (logical-hostname (:make-load-form-fun
220                                (lambda (x)
221                                  (values `(make-logical-hostname
222                                            ,(logical-hostname-name x))
223                                          nil)))
224                               (:copier nil)
225                               (:constructor make-logical-hostname (name)))
226   (name (missing-arg) :type simple-string))
227
228 (defun maybe-extract-logical-hostname (namestr start end)
229   (declare (type simple-base-string namestr)
230            (type index start end))
231   (let ((quoted nil))
232     (do ((index start (1+ index)))
233         ((= index end)
234          (values nil start))
235       (if quoted
236           (setf quoted nil)
237           (case (schar namestr index)
238             (#\\
239              (setf quoted t))
240             (#\:
241              (return (values (make-logical-hostname
242                               (remove-backslashes namestr start index))
243                              (1+ index)))))))))
244
245 (defun parse-unix-namestring (namestr start end)
246   (declare (type simple-base-string namestr)
247            (type index start end))
248   (multiple-value-bind (absolute pieces) (split-at-slashes namestr start end)
249     (let ((logical-hostname
250            (if absolute
251                nil
252                (let ((first (car pieces)))
253                  (multiple-value-bind (logical-hostname new-start)
254                      (maybe-extract-logical-hostname namestr
255                                                      (car first)
256                                                      (cdr first))
257                    (when logical-hostname
258                      (setf absolute t)
259                      (setf (car first) new-start))
260                    logical-hostname)))))
261       (declare (type (or null logical-hostname) logical-hostname))
262       (multiple-value-bind (name type version)
263           (let* ((tail (car (last pieces)))
264                  (tail-start (car tail))
265                  (tail-end (cdr tail)))
266             (unless (= tail-start tail-end)
267               (setf pieces (butlast pieces))
268               (extract-name-type-and-version namestr tail-start tail-end)))
269
270         (when (stringp name)
271           (let ((position (position-if (lambda (char)
272                                          (or (char= char (code-char 0))
273                                              (char= char #\/)))
274                                        name)))
275             (when position
276               (error 'namestring-parse-error
277                      :complaint "can't embed #\\Nul or #\\/ in Unix namestring"
278                      :namestring namestr
279                      :offset position))))
280         
281         ;; Now we have everything we want. So return it.
282         (values nil ; no host for Unix namestrings
283                 nil ; no device for Unix namestrings
284                 (collect ((dirs))
285                   (when logical-hostname
286                     (dirs logical-hostname))
287                   (dolist (piece pieces)
288                     (let ((piece-start (car piece))
289                           (piece-end (cdr piece)))
290                       (unless (= piece-start piece-end)
291                         (cond ((string= namestr ".."
292                                         :start1 piece-start
293                                         :end1 piece-end)
294                                (dirs :up))
295                               ((string= namestr "**"
296                                         :start1 piece-start
297                                         :end1 piece-end)
298                                (dirs :wild-inferiors))
299                               (t
300                                (dirs (maybe-make-pattern namestr
301                                                          piece-start
302                                                          piece-end)))))))
303                   (cond (absolute
304                          (cons :absolute (dirs)))
305                         ((dirs)
306                          (cons :relative (dirs)))
307                         (t
308                          nil)))
309                 name
310                 type
311                 version)))))
312
313 (/show0 "filesys.lisp 300")
314
315 (defun unparse-unix-host (pathname)
316   (declare (type pathname pathname)
317            (ignore pathname))
318   "Unix")
319
320 (defun unparse-unix-piece (thing)
321   (etypecase thing
322     ((member :wild) "*")
323     (simple-string
324      (let* ((srclen (length thing))
325             (dstlen srclen))
326        (dotimes (i srclen)
327          (case (schar thing i)
328            ((#\* #\? #\[)
329             (incf dstlen))))
330        (let ((result (make-string dstlen))
331              (dst 0))
332          (dotimes (src srclen)
333            (let ((char (schar thing src)))
334              (case char
335                ((#\* #\? #\[)
336                 (setf (schar result dst) #\\)
337                 (incf dst)))
338              (setf (schar result dst) char)
339              (incf dst)))
340          result)))
341     (pattern
342      (collect ((strings))
343        (dolist (piece (pattern-pieces thing))
344          (etypecase piece
345            (simple-string
346             (strings piece))
347            (symbol
348             (ecase piece
349               (:multi-char-wild
350                (strings "*"))
351               (:single-char-wild
352                (strings "?"))))
353            (cons
354             (case (car piece)
355               (:character-set
356                (strings "[")
357                (strings (cdr piece))
358                (strings "]"))
359               (t
360                (error "invalid pattern piece: ~S" piece))))))
361        (apply #'concatenate
362               'simple-string
363               (strings))))))
364
365 (defun unparse-unix-directory-list (directory)
366   (declare (type list directory))
367   (collect ((pieces))
368     (when directory
369       (ecase (pop directory)
370         (:absolute
371          (cond ((logical-hostname-p (car directory))
372                 ;; FIXME: The old CMU CL "search list" extension is
373                 ;; gone, but the old machinery is still being used
374                 ;; clumsily here and elsewhere, to represent anything
375                 ;; which belongs before a colon prefix in the ANSI
376                 ;; pathname machinery. This should be cleaned up,
377                 ;; using simpler machinery with more mnemonic names.
378                 (pieces (logical-hostname-name (pop directory)))
379                 (pieces ":"))
380                (t
381                 (pieces "/"))))
382         (:relative
383          ;; nothing special
384          ))
385       (dolist (dir directory)
386         (typecase dir
387           ((member :up)
388            (pieces "../"))
389           ((member :back)
390            (error ":BACK cannot be represented in namestrings."))
391           ((member :wild-inferiors)
392            (pieces "**/"))
393           ((or simple-string pattern)
394            (pieces (unparse-unix-piece dir))
395            (pieces "/"))
396           (t
397            (error "invalid directory component: ~S" dir)))))
398     (apply #'concatenate 'simple-string (pieces))))
399
400 (defun unparse-unix-directory (pathname)
401   (declare (type pathname pathname))
402   (unparse-unix-directory-list (%pathname-directory pathname)))
403
404 (defun unparse-unix-file (pathname)
405   (declare (type pathname pathname))
406   (collect ((strings))
407     (let* ((name (%pathname-name pathname))
408            (type (%pathname-type pathname))
409            (type-supplied (not (or (null type) (eq type :unspecific)))))
410       ;; Note: by ANSI 19.3.1.1.5, we ignore the version slot when
411       ;; translating logical pathnames to a filesystem without
412       ;; versions (like Unix).
413       (when name
414         (strings (unparse-unix-piece name)))
415       (when type-supplied
416         (unless name
417           (error "cannot specify the type without a file: ~S" pathname))
418         (strings ".")
419         (strings (unparse-unix-piece type))))
420     (apply #'concatenate 'simple-string (strings))))
421
422 (/show0 "filesys.lisp 406")
423
424 (defun unparse-unix-namestring (pathname)
425   (declare (type pathname pathname))
426   (concatenate 'simple-string
427                (unparse-unix-directory pathname)
428                (unparse-unix-file pathname)))
429
430 (defun unparse-unix-enough (pathname defaults)
431   (declare (type pathname pathname defaults))
432   (flet ((lose ()
433            (error "~S cannot be represented relative to ~S."
434                   pathname defaults)))
435     (collect ((strings))
436       (let* ((pathname-directory (%pathname-directory pathname))
437              (defaults-directory (%pathname-directory defaults))
438              (prefix-len (length defaults-directory))
439              (result-directory
440               (cond ((and (> prefix-len 1)
441                           (>= (length pathname-directory) prefix-len)
442                           (compare-component (subseq pathname-directory
443                                                      0 prefix-len)
444                                              defaults-directory))
445                      ;; Pathname starts with a prefix of default. So
446                      ;; just use a relative directory from then on out.
447                      (cons :relative (nthcdr prefix-len pathname-directory)))
448                     ((eq (car pathname-directory) :absolute)
449                      ;; We are an absolute pathname, so we can just use it.
450                      pathname-directory)
451                     (t
452                      ;; We are a relative directory. So we lose.
453                      (lose)))))
454         (strings (unparse-unix-directory-list result-directory)))
455       (let* ((pathname-version (%pathname-version pathname))
456              (version-needed (and pathname-version
457                                   (not (eq pathname-version :newest))))
458              (pathname-type (%pathname-type pathname))
459              (type-needed (or version-needed
460                               (and pathname-type
461                                    (not (eq pathname-type :unspecific)))))
462              (pathname-name (%pathname-name pathname))
463              (name-needed (or type-needed
464                               (and pathname-name
465                                    (not (compare-component pathname-name
466                                                            (%pathname-name
467                                                             defaults)))))))
468         (when name-needed
469           (unless pathname-name (lose))
470           (strings (unparse-unix-piece pathname-name)))
471         (when type-needed
472           (when (or (null pathname-type) (eq pathname-type :unspecific))
473             (lose))
474           (strings ".")
475           (strings (unparse-unix-piece pathname-type)))
476         (when version-needed
477           (typecase pathname-version
478             ((member :wild)
479              (strings ".*"))
480             (integer
481              (strings (format nil ".~D" pathname-version)))
482             (t
483              (lose)))))
484       (apply #'concatenate 'simple-string (strings)))))
485 \f
486 ;;;; wildcard matching stuff
487
488 ;;; Return a list of all the Lispy filenames (not including e.g. the
489 ;;; Unix magic "." and "..") in the directory named by DIRECTORY-NAME.
490 (defun directory-lispy-filenames (directory-name)
491   (with-alien ((adlf (* c-string)
492                      (alien-funcall (extern-alien
493                                      "alloc_directory_lispy_filenames"
494                                      (function (* c-string) c-string))
495                                     directory-name)))
496     (if (null-alien adlf)
497         (error 'simple-file-error
498                :pathname directory-name
499                :format-control "~@<couldn't read directory ~S: ~2I~_~A~:>"
500                :format-arguments (list directory-name (strerror)))
501         (unwind-protect
502             (c-strings->string-list adlf)
503           (alien-funcall (extern-alien "free_directory_lispy_filenames"
504                                        (function void (* c-string)))
505                          adlf)))))
506
507 (/show0 "filesys.lisp 498")
508
509 (defmacro !enumerate-matches ((var pathname &optional result
510                                    &key (verify-existence t)
511                                    (follow-links t))
512                               &body body)
513   `(block nil
514      (%enumerate-matches (pathname ,pathname)
515                          ,verify-existence
516                          ,follow-links
517                          (lambda (,var) ,@body))
518      ,result))
519
520 (/show0 "filesys.lisp 500")
521
522 ;;; Call FUNCTION on matches.
523 (defun %enumerate-matches (pathname verify-existence follow-links function)
524   (/noshow0 "entering %ENUMERATE-MATCHES")
525   (when (pathname-type pathname)
526     (unless (pathname-name pathname)
527       (error "cannot supply a type without a name:~%  ~S" pathname)))
528   (when (and (integerp (pathname-version pathname))
529              (member (pathname-type pathname) '(nil :unspecific)))
530     (error "cannot supply a version without a type:~%  ~S" pathname))
531   (let ((directory (pathname-directory pathname)))
532     (/noshow0 "computed DIRECTORY")
533     (if directory
534         (ecase (first directory)
535           (:absolute
536            (/noshow0 "absolute directory")
537            (%enumerate-directories "/" (rest directory) pathname
538                                    verify-existence follow-links
539                                    nil function))
540           (:relative
541            (/noshow0 "relative directory")
542            (%enumerate-directories "" (rest directory) pathname
543                                    verify-existence follow-links
544                                    nil function)))
545         (%enumerate-files "" pathname verify-existence function))))
546
547 ;;; Call FUNCTION on directories.
548 (defun %enumerate-directories (head tail pathname verify-existence
549                                follow-links nodes function)
550   (declare (simple-string head))
551   (macrolet ((unix-xstat (name)
552                `(if follow-links
553                     (sb!unix:unix-stat ,name)
554                     (sb!unix:unix-lstat ,name)))
555              (with-directory-node-noted ((head) &body body)
556                `(multiple-value-bind (res dev ino mode)
557                     (unix-xstat ,head)
558                   (when (and res (eql (logand mode sb!unix:s-ifmt)
559                                       sb!unix:s-ifdir))
560                     (let ((nodes (cons (cons dev ino) nodes)))
561                       ,@body))))
562              (with-directory-node-removed ((head) &body body)
563                `(multiple-value-bind (res dev ino mode)
564                     (unix-xstat ,head)
565                   (when (and res (eql (logand mode sb!unix:s-ifmt)
566                                       sb!unix:s-ifdir))
567                     (let ((nodes (remove (cons dev ino) nodes :test #'equal)))
568                       ,@body)))))
569     (if tail
570         (let ((piece (car tail)))
571           (etypecase piece
572             (simple-string
573              (let ((head (concatenate 'string head piece)))
574                (with-directory-node-noted (head)
575                  (%enumerate-directories (concatenate 'string head "/")
576                                          (cdr tail) pathname
577                                          verify-existence follow-links
578                                          nodes function))))
579             ((member :wild-inferiors)
580              (%enumerate-directories head (rest tail) pathname
581                                      verify-existence follow-links
582                                      nodes function)
583              (dolist (name (ignore-errors (directory-lispy-filenames head)))
584                (let ((subdir (concatenate 'string head name)))
585                  (multiple-value-bind (res dev ino mode)
586                      (unix-xstat subdir)
587                    (declare (type (or fixnum null) mode))
588                    (when (and res (eql (logand mode sb!unix:s-ifmt)
589                                        sb!unix:s-ifdir))
590                      (unless (dolist (dir nodes nil)
591                                (when (and (eql (car dir) dev)
592                                           (eql (cdr dir) ino))
593                                  (return t)))
594                        (let ((nodes (cons (cons dev ino) nodes))
595                              (subdir (concatenate 'string subdir "/")))
596                          (%enumerate-directories subdir tail pathname
597                                                  verify-existence follow-links
598                                                  nodes function))))))))
599             ((or pattern (member :wild))
600              (dolist (name (directory-lispy-filenames head))
601                (when (or (eq piece :wild) (pattern-matches piece name))
602                  (let ((subdir (concatenate 'string head name)))
603                    (multiple-value-bind (res dev ino mode)
604                        (unix-xstat subdir)
605                      (declare (type (or fixnum null) mode))
606                      (when (and res
607                                 (eql (logand mode sb!unix:s-ifmt)
608                                      sb!unix:s-ifdir))
609                        (let ((nodes (cons (cons dev ino) nodes))
610                              (subdir (concatenate 'string subdir "/")))
611                          (%enumerate-directories subdir (rest tail) pathname
612                                                  verify-existence follow-links
613                                                  nodes function))))))))
614           ((member :up)
615              (with-directory-node-removed (head)
616              (let ((head (concatenate 'string head "..")))
617                (with-directory-node-noted (head)
618                  (%enumerate-directories (concatenate 'string head "/")
619                                          (rest tail) pathname
620                                          verify-existence follow-links
621                                          nodes function)))))))
622         (%enumerate-files head pathname verify-existence function))))
623
624 ;;; Call FUNCTION on files.
625 (defun %enumerate-files (directory pathname verify-existence function)
626   (declare (simple-string directory))
627   (/noshow0 "entering %ENUMERATE-FILES")
628   (let ((name (%pathname-name pathname))
629         (type (%pathname-type pathname))
630         (version (%pathname-version pathname)))
631     (/noshow0 "computed NAME, TYPE, and VERSION")
632     (cond ((member name '(nil :unspecific))
633            (/noshow0 "UNSPECIFIC, more or less")
634            (when (or (not verify-existence)
635                      (sb!unix:unix-file-kind directory))
636              (funcall function directory)))
637           ((or (pattern-p name)
638                (pattern-p type)
639                (eq name :wild)
640                (eq type :wild))
641            (/noshow0 "WILD, more or less")
642            ;; I IGNORE-ERRORS here just because the original CMU CL
643            ;; code did. I think the intent is that it's not an error
644            ;; to request matches to a wild pattern when no matches
645            ;; exist, but I haven't tried to figure out whether
646            ;; everything is kosher. (E.g. what if we try to match a
647            ;; wildcard but we don't have permission to read one of the
648            ;; relevant directories?) -- WHN 2001-04-17
649            (dolist (complete-filename (ignore-errors
650                                         (directory-lispy-filenames directory)))
651              (multiple-value-bind
652                  (file-name file-type file-version)
653                  (let ((*ignore-wildcards* t))
654                    (extract-name-type-and-version
655                     complete-filename 0 (length complete-filename)))
656                (when (and (components-match file-name name)
657                           (components-match file-type type)
658                           (components-match file-version version))
659                  (funcall function
660                           (concatenate 'string
661                                        directory
662                                        complete-filename))))))
663           (t
664            (/noshow0 "default case")
665            (let ((file (concatenate 'string directory name)))
666              (/noshow "computed basic FILE")
667              (unless (or (null type) (eq type :unspecific))
668                (/noshow0 "tweaking FILE for more-or-less-:UNSPECIFIC case")
669                (setf file (concatenate 'string file "." type)))
670              (unless (member version '(nil :newest :wild))
671                (/noshow0 "tweaking FILE for more-or-less-:WILD case")
672                (setf file (concatenate 'string file "."
673                                        (quick-integer-to-string version))))
674              (/noshow0 "finished possibly tweaking FILE")
675              (when (or (not verify-existence)
676                        (sb!unix:unix-file-kind file t))
677                (/noshow0 "calling FUNCTION on FILE")
678                (funcall function file)))))))
679
680 (/noshow0 "filesys.lisp 603")
681
682 ;;; FIXME: Why do we need this?
683 (defun quick-integer-to-string (n)
684   (declare (type integer n))
685   (cond ((not (fixnump n))
686          (write-to-string n :base 10 :radix nil))
687         ((zerop n) "0")
688         ((eql n 1) "1")
689         ((minusp n)
690          (concatenate 'simple-string "-"
691                       (the simple-string (quick-integer-to-string (- n)))))
692         (t
693          (do* ((len (1+ (truncate (integer-length n) 3)))
694                (res (make-string len))
695                (i (1- len) (1- i))
696                (q n)
697                (r 0))
698               ((zerop q)
699                (incf i)
700                (replace res res :start2 i :end2 len)
701                (shrink-vector res (- len i)))
702            (declare (simple-string res)
703                     (fixnum len i r q))
704            (multiple-value-setq (q r) (truncate q 10))
705            (setf (schar res i) (schar "0123456789" r))))))
706 \f
707 ;;;; UNIX-NAMESTRING
708
709 (defun empty-relative-pathname-spec-p (x)
710   (or (equal x "")
711       (and (pathnamep x)
712            (or (equal (pathname-directory x) '(:relative))
713                ;; KLUDGE: I'm not sure this second check should really
714                ;; have to be here. But on sbcl-0.6.12.7,
715                ;; (PATHNAME-DIRECTORY (PATHNAME "")) is NIL, and
716                ;; (PATHNAME "") seems to act like an empty relative
717                ;; pathname, so in order to work with that, I test
718                ;; for NIL here. -- WHN 2001-05-18
719                (null (pathname-directory x)))
720            (null (pathname-name x))
721            (null (pathname-type x)))
722       ;; (The ANSI definition of "pathname specifier" has 
723       ;; other cases, but none of them seem to admit the possibility
724       ;; of being empty and relative.)
725       ))
726
727 ;;; Convert PATHNAME into a string that can be used with UNIX system
728 ;;; calls, or return NIL if no match is found. Wild-cards are expanded.
729 (defun unix-namestring (pathname-spec &optional (for-input t))
730   ;; The ordinary rules of converting Lispy paths to Unix paths break
731   ;; down for the current working directory, which Lisp thinks of as
732   ;; "" (more or less, and modulo ANSI's *DEFAULT-PATHNAME-DEFAULTS*,
733   ;; which unfortunately SBCL, as of sbcl-0.6.12.8, basically ignores)
734   ;; and Unix thinks of as ".". Since we're at the interface between
735   ;; Unix system calls and things like ENSURE-DIRECTORIES-EXIST which
736   ;; think the Lisp way, we perform the conversion.
737   ;;
738   ;; (FIXME: The *right* way to deal with this special case is to
739   ;; merge PATHNAME-SPEC with *DEFAULT-PATHNAME-DEFAULTS* here, after
740   ;; which it's not a relative pathname any more so the special case
741   ;; is no longer an issue. But until *DEFAULT-PATHNAME-DEFAULTS*
742   ;; works, we use this hack.)
743   (if (empty-relative-pathname-spec-p pathname-spec)
744       "."
745       ;; Otherwise, the ordinary rules apply.
746       (let* ((namestring (physicalize-pathname (pathname pathname-spec)))
747              (matches nil)) ; an accumulator for actual matches
748         (!enumerate-matches (match namestring nil :verify-existence for-input)
749           (push match matches))
750         (case (length matches)
751           (0 nil)
752           (1 (first matches))
753           (t (error 'simple-file-error
754                     :format-control "~S is ambiguous:~{~%  ~A~}"
755                     :format-arguments (list pathname-spec matches)))))))
756 \f
757 ;;;; TRUENAME and PROBE-FILE
758
759 ;;; This is only trivially different from PROBE-FILE, which is silly
760 ;;; but ANSI.
761 (defun truename (pathname)
762   #!+sb-doc
763   "Return the pathname for the actual file described by PATHNAME.
764   An error of type FILE-ERROR is signalled if no such file exists,
765   or the pathname is wild.
766
767   Under Unix, the TRUENAME of a broken symlink is considered to be
768   the name of the broken symlink itself."
769   (if (wild-pathname-p pathname)
770       (error 'simple-file-error
771              :format-control "can't use a wild pathname here"
772              :pathname pathname)
773       (let ((result (probe-file pathname)))
774         (unless result
775           (error 'simple-file-error
776                  :pathname pathname
777                  :format-control "The file ~S does not exist."
778                  :format-arguments (list (namestring pathname))))
779         result)))
780
781 ;;; If PATHNAME exists, return its truename, otherwise NIL.
782 (defun probe-file (pathname)
783   #!+sb-doc
784   "Return a pathname which is the truename of the file if it exists, or NIL
785   otherwise. An error of type FILE-ERROR is signaled if pathname is wild."
786   (when (wild-pathname-p pathname)
787     (error 'simple-file-error
788            :pathname pathname
789            :format-control "can't use a wild pathname here"))
790   (let* ((defaulted-pathname (merge-pathnames
791                               pathname
792                               (sane-default-pathname-defaults)))
793          (namestring (unix-namestring defaulted-pathname t)))
794     (when (and namestring (sb!unix:unix-file-kind namestring t))
795       (let ((trueishname (sb!unix:unix-resolve-links namestring)))
796         (when trueishname
797           (let ((*ignore-wildcards* t))
798             (pathname (sb!unix:unix-simplify-pathname trueishname))))))))
799 \f
800 ;;;; miscellaneous other operations
801
802 (/show0 "filesys.lisp 700")
803
804 (defun rename-file (file new-name)
805   #!+sb-doc
806   "Rename FILE to have the specified NEW-NAME. If FILE is a stream open to a
807   file, then the associated file is renamed."
808   (let* ((original (truename file))
809          (original-namestring (unix-namestring original t))
810          (new-name (merge-pathnames new-name original))
811          (new-namestring (unix-namestring new-name nil)))
812     (unless new-namestring
813       (error 'simple-file-error
814              :pathname new-name
815              :format-control "~S can't be created."
816              :format-arguments (list new-name)))
817     (multiple-value-bind (res error)
818         (sb!unix:unix-rename original-namestring new-namestring)
819       (unless res
820         (error 'simple-file-error
821                :pathname new-name
822                :format-control "~@<couldn't rename ~2I~_~A ~I~_to ~2I~_~A: ~
823                                 ~I~_~A~:>"
824                :format-arguments (list original new-name (strerror error))))
825       (when (streamp file)
826         (file-name file new-namestring))
827       (values new-name original (truename new-name)))))
828
829 (defun delete-file (file)
830   #!+sb-doc
831   "Delete the specified FILE."
832   (let ((namestring (unix-namestring file t)))
833     (when (streamp file)
834       (close file :abort t))
835     (unless namestring
836       (error 'simple-file-error
837              :pathname file
838              :format-control "~S doesn't exist."
839              :format-arguments (list file)))
840     (multiple-value-bind (res err) (sb!unix:unix-unlink namestring)
841       (unless res
842         (simple-file-perror "couldn't delete ~A" namestring err))))
843   t)
844 \f
845 ;;; (This is an ANSI Common Lisp function.) 
846 ;;;
847 ;;; This is obtained from the logical name \"home:\", which is set
848 ;;; up for us at initialization time.
849 (defun user-homedir-pathname (&optional host)
850   "Return the home directory of the user as a pathname."
851   (declare (ignore host))
852   ;; Note: CMU CL did #P"home:" here instead of using a call to
853   ;; PATHNAME. Delaying construction of the pathname until we're
854   ;; running in a target Lisp lets us avoid figuring out how to dump
855   ;; cross-compilation host Lisp PATHNAME objects into a target Lisp
856   ;; object file. It also might have a small positive effect on
857   ;; efficiency, in that we don't allocate a PATHNAME we don't need,
858   ;; but it it could also have a larger negative effect. Hopefully
859   ;; it'll be OK. -- WHN 19990714
860   (pathname "home:"))
861
862 (defun file-write-date (file)
863   #!+sb-doc
864   "Return file's creation date, or NIL if it doesn't exist.
865  An error of type file-error is signaled if file is a wild pathname"
866   (if (wild-pathname-p file)
867       ;; FIXME: This idiom appears many times in this file. Perhaps it
868       ;; should turn into (CANNOT-BE-WILD-PATHNAME FILE). (C-B-W-P
869       ;; should be a macro, not a function, so that the error message
870       ;; is reported as coming from e.g. FILE-WRITE-DATE instead of
871       ;; from CANNOT-BE-WILD-PATHNAME itself.)
872       (error 'simple-file-error
873              :pathname file
874              :format-control "bad place for a wild pathname")
875       (let ((name (unix-namestring file t)))
876         (when name
877           (multiple-value-bind
878               (res dev ino mode nlink uid gid rdev size atime mtime)
879               (sb!unix:unix-stat name)
880             (declare (ignore dev ino mode nlink uid gid rdev size atime))
881             (when res
882               (+ unix-to-universal-time mtime)))))))
883
884 (defun file-author (file)
885   #!+sb-doc
886   "Return the file author as a string, or NIL if the author cannot be
887  determined. Signal an error of type FILE-ERROR if FILE doesn't exist,
888  or FILE is a wild pathname."
889   (if (wild-pathname-p file)
890       (error 'simple-file-error
891              :pathname file
892              "bad place for a wild pathname")
893       (let ((name (unix-namestring (pathname file) t)))
894         (unless name
895           (error 'simple-file-error
896                  :pathname file
897                  :format-control "~S doesn't exist."
898                  :format-arguments (list file)))
899         (multiple-value-bind (winp dev ino mode nlink uid)
900             (sb!unix:unix-stat name)
901           (declare (ignore dev ino mode nlink))
902           (and winp (sb!unix:uid-username uid))))))
903 \f
904 ;;;; DIRECTORY
905
906 (/show0 "filesys.lisp 800")
907
908 (defun directory (pathname &key)
909   #!+sb-doc
910   "Return a list of PATHNAMEs, each the TRUENAME of a file that matched the
911    given pathname. Note that the interaction between this ANSI-specified
912    TRUENAMEing and the semantics of the Unix filesystem (symbolic links..)
913    means this function can sometimes return files which don't have the same
914    directory as PATHNAME."
915   (let (;; We create one entry in this hash table for each truename,
916         ;; as an asymptotically efficient way of removing duplicates
917         ;; (which can arise when e.g. multiple symlinks map to the
918         ;; same truename).
919         (truenames (make-hash-table :test #'equal))
920         (merged-pathname (merge-pathnames pathname
921                                           *default-pathname-defaults*)))
922     (!enumerate-matches (match merged-pathname)
923       (let ((*ignore-wildcards* t)
924             (truename (truename (if (eq (sb!unix:unix-file-kind match)
925                                         :directory)
926                                     (concatenate 'string match "/")
927                                     match))))
928         (setf (gethash (namestring truename) truenames)
929               truename)))
930     (mapcar #'cdr
931             ;; Sorting isn't required by the ANSI spec, but sorting
932             ;; into some canonical order seems good just on the
933             ;; grounds that the implementation should have repeatable
934             ;; behavior when possible.
935             (sort (loop for name being each hash-key in truenames
936                         using (hash-value truename)
937                         collect (cons name truename))
938                   #'string<
939                   :key #'car))))
940 \f
941 (/show0 "filesys.lisp 899")
942
943 ;;; predicate to order pathnames by; goes by name
944 (defun pathname-order (x y)
945   (let ((xn (%pathname-name x))
946         (yn (%pathname-name y)))
947     (if (and xn yn)
948         (let ((res (string-lessp xn yn)))
949           (cond ((not res) nil)
950                 ((= res (length (the simple-string xn))) t)
951                 ((= res (length (the simple-string yn))) nil)
952                 (t t)))
953         xn)))
954 \f
955 (defun ensure-directories-exist (pathspec &key verbose (mode #o777))
956   #!+sb-doc
957   "Test whether the directories containing the specified file
958   actually exist, and attempt to create them if they do not.
959   The MODE argument is a CMUCL/SBCL-specific extension to control
960   the Unix permission bits."
961   (let ((pathname (physicalize-pathname (pathname pathspec)))
962         (created-p nil))
963     (when (wild-pathname-p pathname)
964       (error 'simple-file-error
965              :format-control "bad place for a wild pathname"
966              :pathname pathspec))
967     (let ((dir (pathname-directory pathname)))
968       (loop for i from 1 upto (length dir)
969             do (let ((newpath (make-pathname
970                                :host (pathname-host pathname)
971                                :device (pathname-device pathname)
972                                :directory (subseq dir 0 i))))
973                  (unless (probe-file newpath)
974                    (let ((namestring (namestring newpath)))
975                      (when verbose
976                        (format *standard-output*
977                                "~&creating directory: ~A~%"
978                                namestring))
979                      (sb!unix:unix-mkdir namestring mode)
980                      (unless (probe-file namestring)
981                        (error 'simple-file-error
982                               :pathname pathspec
983                               :format-control "can't create directory ~A"
984                               :format-arguments (list namestring)))
985                      (setf created-p t)))))
986       (values pathname created-p))))
987
988 (/show0 "filesys.lisp 1000")