0.7.1.48:
[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 ;;; FIXME this should signal file-error if the pathname is wild, whether
730 ;;; or not it turns out to have only one match.  Fix post 0.7.2
731 (defun unix-namestring (pathname-spec &optional (for-input t))
732   (let* ((namestring (physicalize-pathname (merge-pathnames pathname-spec)))
733          (matches nil)) ; an accumulator for actual matches
734     (!enumerate-matches (match namestring nil :verify-existence for-input)
735                         (push match matches))
736     (case (length matches)
737       (0 nil)
738       (1 (first matches))
739       (t (error 'simple-file-error
740                 :format-control "~S is ambiguous:~{~%  ~A~}"
741                 :format-arguments (list pathname-spec matches))))))
742 \f
743 ;;;; TRUENAME and PROBE-FILE
744
745 ;;; This is only trivially different from PROBE-FILE, which is silly
746 ;;; but ANSI.
747 (defun truename (pathname)
748   #!+sb-doc
749   "Return the pathname for the actual file described by PATHNAME.
750   An error of type FILE-ERROR is signalled if no such file exists,
751   or the pathname is wild.
752
753   Under Unix, the TRUENAME of a broken symlink is considered to be
754   the name of the broken symlink itself."
755   (if (wild-pathname-p pathname)
756       (error 'simple-file-error
757              :format-control "can't use a wild pathname here"
758              :pathname pathname)
759       (let ((result (probe-file pathname)))
760         (unless result
761           (error 'simple-file-error
762                  :pathname pathname
763                  :format-control "The file ~S does not exist."
764                  :format-arguments (list (namestring pathname))))
765         result)))
766
767 ;;; If PATHNAME exists, return its truename, otherwise NIL.
768 (defun probe-file (pathname)
769   #!+sb-doc
770   "Return a pathname which is the truename of the file if it exists, or NIL
771   otherwise. An error of type FILE-ERROR is signaled if pathname is wild."
772   (when (wild-pathname-p pathname)
773     (error 'simple-file-error
774            :pathname pathname
775            :format-control "can't use a wild pathname here"))
776   (let* ((defaulted-pathname (merge-pathnames
777                               pathname
778                               (sane-default-pathname-defaults)))
779          (namestring (unix-namestring defaulted-pathname t)))
780     (when (and namestring (sb!unix:unix-file-kind namestring t))
781       (let ((trueishname (sb!unix:unix-resolve-links namestring)))
782         (when trueishname
783           (let ((*ignore-wildcards* t))
784             (pathname (sb!unix:unix-simplify-pathname trueishname))))))))
785 \f
786 ;;;; miscellaneous other operations
787
788 (/show0 "filesys.lisp 700")
789
790 (defun rename-file (file new-name)
791   #!+sb-doc
792   "Rename FILE to have the specified NEW-NAME. If FILE is a stream open to a
793   file, then the associated file is renamed."
794   (let* ((original (truename file))
795          (original-namestring (unix-namestring original t))
796          (new-name (merge-pathnames new-name original))
797          (new-namestring (unix-namestring new-name nil)))
798     (unless new-namestring
799       (error 'simple-file-error
800              :pathname new-name
801              :format-control "~S can't be created."
802              :format-arguments (list new-name)))
803     (multiple-value-bind (res error)
804         (sb!unix:unix-rename original-namestring new-namestring)
805       (unless res
806         (error 'simple-file-error
807                :pathname new-name
808                :format-control "~@<couldn't rename ~2I~_~A ~I~_to ~2I~_~A: ~
809                                 ~I~_~A~:>"
810                :format-arguments (list original new-name (strerror error))))
811       (when (streamp file)
812         (file-name file new-namestring))
813       (values new-name original (truename new-name)))))
814
815 (defun delete-file (file)
816   #!+sb-doc
817   "Delete the specified FILE."
818   (let ((namestring (unix-namestring file t)))
819     (when (streamp file)
820       (close file :abort t))
821     (unless namestring
822       (error 'simple-file-error
823              :pathname file
824              :format-control "~S doesn't exist."
825              :format-arguments (list file)))
826     (multiple-value-bind (res err) (sb!unix:unix-unlink namestring)
827       (unless res
828         (simple-file-perror "couldn't delete ~A" namestring err))))
829   t)
830 \f
831 ;;; (This is an ANSI Common Lisp function.) 
832 ;;;
833 ;;; This is obtained from the logical name \"home:\", which is set
834 ;;; up for us at initialization time.
835 (defun user-homedir-pathname (&optional host)
836   "Return the home directory of the user as a pathname."
837   (declare (ignore host))
838   ;; Note: CMU CL did #P"home:" here instead of using a call to
839   ;; PATHNAME. Delaying construction of the pathname until we're
840   ;; running in a target Lisp lets us avoid figuring out how to dump
841   ;; cross-compilation host Lisp PATHNAME objects into a target Lisp
842   ;; object file. It also might have a small positive effect on
843   ;; efficiency, in that we don't allocate a PATHNAME we don't need,
844   ;; but it it could also have a larger negative effect. Hopefully
845   ;; it'll be OK. -- WHN 19990714
846   (pathname "home:"))
847
848 (defun file-write-date (file)
849   #!+sb-doc
850   "Return file's creation date, or NIL if it doesn't exist.
851  An error of type file-error is signaled if file is a wild pathname"
852   (if (wild-pathname-p file)
853       ;; FIXME: This idiom appears many times in this file. Perhaps it
854       ;; should turn into (CANNOT-BE-WILD-PATHNAME FILE). (C-B-W-P
855       ;; should be a macro, not a function, so that the error message
856       ;; is reported as coming from e.g. FILE-WRITE-DATE instead of
857       ;; from CANNOT-BE-WILD-PATHNAME itself.)
858       (error 'simple-file-error
859              :pathname file
860              :format-control "bad place for a wild pathname")
861       (let ((name (unix-namestring file t)))
862         (when name
863           (multiple-value-bind
864               (res dev ino mode nlink uid gid rdev size atime mtime)
865               (sb!unix:unix-stat name)
866             (declare (ignore dev ino mode nlink uid gid rdev size atime))
867             (when res
868               (+ unix-to-universal-time mtime)))))))
869
870 (defun file-author (file)
871   #!+sb-doc
872   "Return the file author as a string, or NIL if the author cannot be
873  determined. Signal an error of type FILE-ERROR if FILE doesn't exist,
874  or FILE is a wild pathname."
875   (if (wild-pathname-p file)
876       (error 'simple-file-error
877              :pathname file
878              "bad place for a wild pathname")
879       (let ((name (unix-namestring (pathname file) t)))
880         (unless name
881           (error 'simple-file-error
882                  :pathname file
883                  :format-control "~S doesn't exist."
884                  :format-arguments (list file)))
885         (multiple-value-bind (winp dev ino mode nlink uid)
886             (sb!unix:unix-stat name)
887           (declare (ignore dev ino mode nlink))
888           (and winp (sb!unix:uid-username uid))))))
889 \f
890 ;;;; DIRECTORY
891
892 (/show0 "filesys.lisp 800")
893
894 (defun directory (pathname &key)
895   #!+sb-doc
896   "Return a list of PATHNAMEs, each the TRUENAME of a file that matched the
897    given pathname. Note that the interaction between this ANSI-specified
898    TRUENAMEing and the semantics of the Unix filesystem (symbolic links..)
899    means this function can sometimes return files which don't have the same
900    directory as PATHNAME."
901   (let (;; We create one entry in this hash table for each truename,
902         ;; as an asymptotically efficient way of removing duplicates
903         ;; (which can arise when e.g. multiple symlinks map to the
904         ;; same truename).
905         (truenames (make-hash-table :test #'equal))
906         (merged-pathname (merge-pathnames pathname
907                                           *default-pathname-defaults*)))
908     (!enumerate-matches (match merged-pathname)
909       (let ((*ignore-wildcards* t)
910             (truename (truename (if (eq (sb!unix:unix-file-kind match)
911                                         :directory)
912                                     (concatenate 'string match "/")
913                                     match))))
914         (setf (gethash (namestring truename) truenames)
915               truename)))
916     (mapcar #'cdr
917             ;; Sorting isn't required by the ANSI spec, but sorting
918             ;; into some canonical order seems good just on the
919             ;; grounds that the implementation should have repeatable
920             ;; behavior when possible.
921             (sort (loop for name being each hash-key in truenames
922                         using (hash-value truename)
923                         collect (cons name truename))
924                   #'string<
925                   :key #'car))))
926 \f
927 (/show0 "filesys.lisp 899")
928
929 ;;; predicate to order pathnames by; goes by name
930 (defun pathname-order (x y)
931   (let ((xn (%pathname-name x))
932         (yn (%pathname-name y)))
933     (if (and xn yn)
934         (let ((res (string-lessp xn yn)))
935           (cond ((not res) nil)
936                 ((= res (length (the simple-string xn))) t)
937                 ((= res (length (the simple-string yn))) nil)
938                 (t t)))
939         xn)))
940 \f
941 (defun ensure-directories-exist (pathspec &key verbose (mode #o777))
942   #!+sb-doc
943   "Test whether the directories containing the specified file
944   actually exist, and attempt to create them if they do not.
945   The MODE argument is a CMUCL/SBCL-specific extension to control
946   the Unix permission bits."
947   (let ((pathname (physicalize-pathname (pathname pathspec)))
948         (created-p nil))
949     (when (wild-pathname-p pathname)
950       (error 'simple-file-error
951              :format-control "bad place for a wild pathname"
952              :pathname pathspec))
953     (let ((dir (pathname-directory pathname)))
954       (loop for i from 1 upto (length dir)
955             do (let ((newpath (make-pathname
956                                :host (pathname-host pathname)
957                                :device (pathname-device pathname)
958                                :directory (subseq dir 0 i))))
959                  (unless (probe-file newpath)
960                    (let ((namestring (namestring newpath)))
961                      (when verbose
962                        (format *standard-output*
963                                "~&creating directory: ~A~%"
964                                namestring))
965                      (sb!unix:unix-mkdir namestring mode)
966                      (unless (probe-file namestring)
967                        (error 'simple-file-error
968                               :pathname pathspec
969                               :format-control "can't create directory ~A"
970                               :format-arguments (list namestring)))
971                      (setf created-p t)))))
972       (values pathname created-p))))
973
974 (/show0 "filesys.lisp 1000")