0.pre7.39:
[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 (required-argument) :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
486 (/show0 "filesys.lisp 471")
487
488 (def!struct (unix-host
489              (:make-load-form-fun make-unix-host-load-form)
490              (:include host
491                        (parse #'parse-unix-namestring)
492                        (unparse #'unparse-unix-namestring)
493                        (unparse-host #'unparse-unix-host)
494                        (unparse-directory #'unparse-unix-directory)
495                        (unparse-file #'unparse-unix-file)
496                        (unparse-enough #'unparse-unix-enough)
497                        (customary-case :lower))))
498
499 (/show0 "filesys.lisp 486")
500
501 (defvar *unix-host* (make-unix-host))
502
503 (/show0 "filesys.lisp 488")
504
505 (defun make-unix-host-load-form (host)
506   (declare (ignore host))
507   '*unix-host*)
508 \f
509 ;;;; wildcard matching stuff
510
511 ;;; Return a list of all the Lispy filenames (not including e.g. the
512 ;;; Unix magic "." and "..") in the directory named by DIRECTORY-NAME.
513 (defun directory-lispy-filenames (directory-name)
514   (with-alien ((adlf (* c-string)
515                      (alien-funcall (extern-alien
516                                      "alloc_directory_lispy_filenames"
517                                      (function (* c-string) c-string))
518                                     directory-name)))
519     (if (null-alien adlf)
520         (error 'simple-file-error
521                :pathname directory-name
522                :format-control "~@<couldn't read directory ~S: ~2I~_~A~:>"
523                :format-arguments (list directory-name (strerror)))
524         (unwind-protect
525             (c-strings->string-list adlf)
526           (alien-funcall (extern-alien "free_directory_lispy_filenames"
527                                        (function void (* c-string)))
528                          adlf)))))
529
530 (/show0 "filesys.lisp 498")
531
532 (defmacro !enumerate-matches ((var pathname &optional result
533                                    &key (verify-existence t)
534                                    (follow-links t))
535                               &body body)
536   `(block nil
537      (%enumerate-matches (pathname ,pathname)
538                          ,verify-existence
539                          ,follow-links
540                          (lambda (,var) ,@body))
541      ,result))
542
543 (/show0 "filesys.lisp 500")
544
545 ;;; Call FUNCTION on matches.
546 (defun %enumerate-matches (pathname verify-existence follow-links function)
547   (/noshow0 "entering %ENUMERATE-MATCHES")
548   (when (pathname-type pathname)
549     (unless (pathname-name pathname)
550       (error "cannot supply a type without a name:~%  ~S" pathname)))
551   (when (and (integerp (pathname-version pathname))
552              (member (pathname-type pathname) '(nil :unspecific)))
553     (error "cannot supply a version without a type:~%  ~S" pathname))
554   (let ((directory (pathname-directory pathname)))
555     (/noshow0 "computed DIRECTORY")
556     (if directory
557         (ecase (car directory)
558           (:absolute
559            (/noshow0 "absolute directory")
560            (%enumerate-directories "/" (cdr directory) pathname
561                                    verify-existence follow-links
562                                    nil function))
563           (:relative
564            (/noshow0 "relative directory")
565            (%enumerate-directories "" (cdr directory) pathname
566                                    verify-existence follow-links
567                                    nil function)))
568         (%enumerate-files "" pathname verify-existence function))))
569
570 ;;; Call FUNCTION on directories.
571 (defun %enumerate-directories (head tail pathname verify-existence
572                                follow-links nodes function)
573   (declare (simple-string head))
574   (macrolet ((unix-xstat (name)
575                `(if follow-links
576                     (sb!unix:unix-stat ,name)
577                     (sb!unix:unix-lstat ,name)))
578              (with-directory-node-noted ((head) &body body)
579                `(multiple-value-bind (res dev ino mode)
580                     (unix-xstat ,head)
581                   (when (and res (eql (logand mode sb!unix:s-ifmt)
582                                       sb!unix:s-ifdir))
583                     (let ((nodes (cons (cons dev ino) nodes)))
584                       ,@body)))))
585     (if tail
586         (let ((piece (car tail)))
587           (etypecase piece
588             (simple-string
589              (let ((head (concatenate 'string head piece)))
590                (with-directory-node-noted (head)
591                  (%enumerate-directories (concatenate 'string head "/")
592                                          (cdr tail) pathname
593                                          verify-existence follow-links
594                                          nodes function))))
595             ((member :wild-inferiors)
596              (%enumerate-directories head (rest tail) pathname
597                                      verify-existence follow-links
598                                      nodes function)
599              (dolist (name (ignore-errors (directory-lispy-filenames head)))
600                (let ((subdir (concatenate 'string head name)))
601                  (multiple-value-bind (res dev ino mode)
602                      (unix-xstat subdir)
603                    (declare (type (or fixnum null) mode))
604                    (when (and res (eql (logand mode sb!unix:s-ifmt)
605                                        sb!unix:s-ifdir))
606                      (unless (dolist (dir nodes nil)
607                                (when (and (eql (car dir) dev)
608                                           (eql (cdr dir) ino))
609                                  (return t)))
610                        (let ((nodes (cons (cons dev ino) nodes))
611                              (subdir (concatenate 'string subdir "/")))
612                          (%enumerate-directories subdir tail pathname
613                                                  verify-existence follow-links
614                                                  nodes function))))))))
615             ((or pattern (member :wild))
616              (dolist (name (directory-lispy-filenames head))
617                (when (or (eq piece :wild) (pattern-matches piece name))
618                  (let ((subdir (concatenate 'string head name)))
619                    (multiple-value-bind (res dev ino mode)
620                        (unix-xstat subdir)
621                      (declare (type (or fixnum null) mode))
622                      (when (and res
623                                 (eql (logand mode sb!unix:s-ifmt)
624                                      sb!unix:s-ifdir))
625                        (let ((nodes (cons (cons dev ino) nodes))
626                              (subdir (concatenate 'string subdir "/")))
627                          (%enumerate-directories subdir (rest tail) pathname
628                                                  verify-existence follow-links
629                                                  nodes function))))))))
630           ((member :up)
631              (let ((head (concatenate 'string head "..")))
632                (with-directory-node-noted (head)
633                  (%enumerate-directories (concatenate 'string head "/")
634                                          (rest tail) pathname
635                                          verify-existence follow-links
636                                          nodes function))))))
637         (%enumerate-files head pathname verify-existence function))))
638
639 ;;; Call FUNCTION on files.
640 (defun %enumerate-files (directory pathname verify-existence function)
641   (declare (simple-string directory))
642   (/noshow0 "entering %ENUMERATE-FILES")
643   (let ((name (%pathname-name pathname))
644         (type (%pathname-type pathname))
645         (version (%pathname-version pathname)))
646     (/noshow0 "computed NAME, TYPE, and VERSION")
647     (cond ((member name '(nil :unspecific))
648            (/noshow0 "UNSPECIFIC, more or less")
649            (when (or (not verify-existence)
650                      (sb!unix:unix-file-kind directory))
651              (funcall function directory)))
652           ((or (pattern-p name)
653                (pattern-p type)
654                (eq name :wild)
655                (eq type :wild))
656            (/noshow0 "WILD, more or less")
657            ;; I IGNORE-ERRORS here just because the original CMU CL
658            ;; code did. I think the intent is that it's not an error
659            ;; to request matches to a wild pattern when no matches
660            ;; exist, but I haven't tried to figure out whether
661            ;; everything is kosher. (E.g. what if we try to match a
662            ;; wildcard but we don't have permission to read one of the
663            ;; relevant directories?) -- WHN 2001-04-17
664            (dolist (complete-filename (ignore-errors
665                                         (directory-lispy-filenames directory)))
666              (multiple-value-bind
667                  (file-name file-type file-version)
668                  (let ((*ignore-wildcards* t))
669                    (extract-name-type-and-version
670                     complete-filename 0 (length complete-filename)))
671                (when (and (components-match file-name name)
672                           (components-match file-type type)
673                           (components-match file-version version))
674                  (funcall function
675                           (concatenate 'string
676                                        directory
677                                        complete-filename))))))
678           (t
679            (/noshow0 "default case")
680            (let ((file (concatenate 'string directory name)))
681              (/noshow0 "computed basic FILE=..")
682              (/primitive-print file)
683              (unless (or (null type) (eq type :unspecific))
684                (/noshow0 "tweaking FILE for more-or-less-:UNSPECIFIC case")
685                (setf file (concatenate 'string file "." type)))
686              (unless (member version '(nil :newest :wild))
687                (/noshow0 "tweaking FILE for more-or-less-:WILD case")
688                (setf file (concatenate 'string file "."
689                                        (quick-integer-to-string version))))
690              (/noshow0 "finished possibly tweaking FILE=..")
691              (/primitive-print file)
692              (when (or (not verify-existence)
693                        (sb!unix:unix-file-kind file t))
694                (/noshow0 "calling FUNCTION on FILE")
695                (funcall function file)))))))
696
697 (/noshow0 "filesys.lisp 603")
698
699 ;;; FIXME: Why do we need this?
700 (defun quick-integer-to-string (n)
701   (declare (type integer n))
702   (cond ((not (fixnump n))
703          (write-to-string n :base 10 :radix nil))
704         ((zerop n) "0")
705         ((eql n 1) "1")
706         ((minusp n)
707          (concatenate 'simple-string "-"
708                       (the simple-string (quick-integer-to-string (- n)))))
709         (t
710          (do* ((len (1+ (truncate (integer-length n) 3)))
711                (res (make-string len))
712                (i (1- len) (1- i))
713                (q n)
714                (r 0))
715               ((zerop q)
716                (incf i)
717                (replace res res :start2 i :end2 len)
718                (shrink-vector res (- len i)))
719            (declare (simple-string res)
720                     (fixnum len i r q))
721            (multiple-value-setq (q r) (truncate q 10))
722            (setf (schar res i) (schar "0123456789" r))))))
723 \f
724 ;;;; UNIX-NAMESTRING
725
726 (defun empty-relative-pathname-spec-p (x)
727   (or (equal x "")
728       (and (pathnamep x)
729            (or (equal (pathname-directory x) '(:relative))
730                ;; KLUDGE: I'm not sure this second check should really
731                ;; have to be here. But on sbcl-0.6.12.7,
732                ;; (PATHNAME-DIRECTORY (PATHNAME "")) is NIL, and
733                ;; (PATHNAME "") seems to act like an empty relative
734                ;; pathname, so in order to work with that, I test
735                ;; for NIL here. -- WHN 2001-05-18
736                (null (pathname-directory x)))
737            (null (pathname-name x))
738            (null (pathname-type x)))
739       ;; (The ANSI definition of "pathname specifier" has 
740       ;; other cases, but none of them seem to admit the possibility
741       ;; of being empty and relative.)
742       ))
743
744 ;;; Convert PATHNAME into a string that can be used with UNIX system
745 ;;; calls, or return NIL if no match is found. Wild-cards are expanded.
746 (defun unix-namestring (pathname-spec &optional (for-input t))
747   ;; The ordinary rules of converting Lispy paths to Unix paths break
748   ;; down for the current working directory, which Lisp thinks of as
749   ;; "" (more or less, and modulo ANSI's *DEFAULT-PATHNAME-DEFAULTS*,
750   ;; which unfortunately SBCL, as of sbcl-0.6.12.8, basically ignores)
751   ;; and Unix thinks of as ".". Since we're at the interface between
752   ;; Unix system calls and things like ENSURE-DIRECTORIES-EXIST which
753   ;; think the Lisp way, we perform the conversion.
754   ;;
755   ;; (FIXME: The *right* way to deal with this special case is to
756   ;; merge PATHNAME-SPEC with *DEFAULT-PATHNAME-DEFAULTS* here, after
757   ;; which it's not a relative pathname any more so the special case
758   ;; is no longer an issue. But until *DEFAULT-PATHNAME-DEFAULTS*
759   ;; works, we use this hack.)
760   (if (empty-relative-pathname-spec-p pathname-spec)
761       "."
762       ;; Otherwise, the ordinary rules apply.
763       (let* ((namestring (physicalize-pathname (pathname pathname-spec)))
764              (matches nil)) ; an accumulator for actual matches
765         (!enumerate-matches (match namestring nil :verify-existence for-input)
766           (push match matches))
767         (case (length matches)
768           (0 nil)
769           (1 (first matches))
770           (t (error 'simple-file-error
771                     :format-control "~S is ambiguous:~{~%  ~A~}"
772                     :format-arguments (list pathname-spec matches)))))))
773 \f
774 ;;;; TRUENAME and PROBE-FILE
775
776 ;;; This is only trivially different from PROBE-FILE, which is silly
777 ;;; but ANSI.
778 (defun truename (pathname)
779   #!+sb-doc
780   "Return the pathname for the actual file described by PATHNAME.
781   An error of type FILE-ERROR is signalled if no such file exists,
782   or the pathname is wild.
783
784   Under Unix, the TRUENAME of a broken symlink is considered to be
785   the name of the broken symlink itself."
786   (if (wild-pathname-p pathname)
787       (error 'simple-file-error
788              :format-control "can't use a wild pathname here"
789              :pathname pathname)
790       (let ((result (probe-file pathname)))
791         (unless result
792           (error 'simple-file-error
793                  :pathname pathname
794                  :format-control "The file ~S does not exist."
795                  :format-arguments (list (namestring pathname))))
796         result)))
797
798 ;;; If PATHNAME exists, return its truename, otherwise NIL.
799 (defun probe-file (pathname)
800   #!+sb-doc
801   "Return a pathname which is the truename of the file if it exists, or NIL
802   otherwise. An error of type FILE-ERROR is signaled if pathname is wild."
803   (when (wild-pathname-p pathname)
804     (error 'simple-file-error
805            :pathname pathname
806            :format-control "can't use a wild pathname here"))
807   (let* ((defaulted-pathname (merge-pathnames
808                               pathname
809                               (sane-default-pathname-defaults)))
810          (namestring (unix-namestring defaulted-pathname t)))
811     (when (and namestring (sb!unix:unix-file-kind namestring t))
812       (let ((trueishname (sb!unix:unix-resolve-links namestring)))
813         (when trueishname
814           (let ((*ignore-wildcards* t))
815             (pathname (sb!unix:unix-simplify-pathname trueishname))))))))
816 \f
817 ;;;; miscellaneous other operations
818
819 (/show0 "filesys.lisp 700")
820
821 (defun rename-file (file new-name)
822   #!+sb-doc
823   "Rename FILE to have the specified NEW-NAME. If FILE is a stream open to a
824   file, then the associated file is renamed."
825   (let* ((original (truename file))
826          (original-namestring (unix-namestring original t))
827          (new-name (merge-pathnames new-name original))
828          (new-namestring (unix-namestring new-name nil)))
829     (unless new-namestring
830       (error 'simple-file-error
831              :pathname new-name
832              :format-control "~S can't be created."
833              :format-arguments (list new-name)))
834     (multiple-value-bind (res error)
835         (sb!unix:unix-rename original-namestring new-namestring)
836       (unless res
837         (error 'simple-file-error
838                :pathname new-name
839                :format-control "~@<couldn't rename ~2I~_~A ~I~_to ~2I~_~A: ~
840                                 ~I~_~A~:>"
841                :format-arguments (list original new-name (strerror error))))
842       (when (streamp file)
843         (file-name file new-namestring))
844       (values new-name original (truename new-name)))))
845
846 (defun delete-file (file)
847   #!+sb-doc
848   "Delete the specified FILE."
849   (let ((namestring (unix-namestring file t)))
850     (when (streamp file)
851       (close file :abort t))
852     (unless namestring
853       (error 'simple-file-error
854              :pathname file
855              :format-control "~S doesn't exist."
856              :format-arguments (list file)))
857     (multiple-value-bind (res err) (sb!unix:unix-unlink namestring)
858       (unless res
859         (simple-file-perror "couldn't delete ~A" namestring err))))
860   t)
861 \f
862 ;;; (This is an ANSI Common Lisp function.) 
863 ;;;
864 ;;; This is obtained from the logical name \"home:\", which is set
865 ;;; up for us at initialization time.
866 (defun user-homedir-pathname (&optional host)
867   "Return the home directory of the user as a pathname."
868   (declare (ignore host))
869   ;; Note: CMU CL did #P"home:" here instead of using a call to
870   ;; PATHNAME. Delaying construction of the pathname until we're
871   ;; running in a target Lisp lets us avoid figuring out how to dump
872   ;; cross-compilation host Lisp PATHNAME objects into a target Lisp
873   ;; object file. It also might have a small positive effect on
874   ;; efficiency, in that we don't allocate a PATHNAME we don't need,
875   ;; but it it could also have a larger negative effect. Hopefully
876   ;; it'll be OK. -- WHN 19990714
877   (pathname "home:"))
878
879 (defun file-write-date (file)
880   #!+sb-doc
881   "Return file's creation date, or NIL if it doesn't exist.
882  An error of type file-error is signaled if file is a wild pathname"
883   (if (wild-pathname-p file)
884       ;; FIXME: This idiom appears many times in this file. Perhaps it
885       ;; should turn into (CANNOT-BE-WILD-PATHNAME FILE). (C-B-W-P
886       ;; should be a macro, not a function, so that the error message
887       ;; is reported as coming from e.g. FILE-WRITE-DATE instead of
888       ;; from CANNOT-BE-WILD-PATHNAME itself.)
889       (error 'simple-file-error
890              :pathname file
891              :format-control "bad place for a wild pathname")
892       (let ((name (unix-namestring file t)))
893         (when name
894           (multiple-value-bind
895               (res dev ino mode nlink uid gid rdev size atime mtime)
896               (sb!unix:unix-stat name)
897             (declare (ignore dev ino mode nlink uid gid rdev size atime))
898             (when res
899               (+ unix-to-universal-time mtime)))))))
900
901 (defun file-author (file)
902   #!+sb-doc
903   "Return the file author as a string, or nil if the author cannot be
904  determined. Signal an error of type FILE-ERROR if FILE doesn't exist,
905  or FILE is a wild pathname."
906   (if (wild-pathname-p file)
907       (error 'simple-file-error
908              :pathname file
909              "bad place for a wild pathname")
910       (let ((name (unix-namestring (pathname file) t)))
911         (unless name
912           (error 'simple-file-error
913                  :pathname file
914                  :format-control "~S doesn't exist."
915                  :format-arguments (list file)))
916         (multiple-value-bind (winp dev ino mode nlink uid)
917             (sb!unix:unix-stat name)
918           (declare (ignore dev ino mode nlink))
919           (if winp (lookup-login-name uid))))))
920 \f
921 ;;;; DIRECTORY
922
923 (/show0 "filesys.lisp 800")
924
925 (defun directory (pathname &key)
926   #!+sb-doc
927   "Return a list of PATHNAMEs, each the TRUENAME of a file that matched the
928    given pathname. Note that the interaction between this ANSI-specified
929    TRUENAMEing and the semantics of the Unix filesystem (symbolic links..)
930    means this function can sometimes return files which don't have the same
931    directory as PATHNAME."
932   (let (;; We create one entry in this hash table for each truename,
933         ;; as an asymptotically fast way of removing duplicates (which
934         ;; can arise when e.g. multiple symlinks map to the same
935         ;; truename).
936         (truenames (make-hash-table :test #'equal))
937         (merged-pathname (merge-pathnames pathname
938                                           (make-pathname :name :wild
939                                                          :type :wild
940                                                          :version :wild))))
941     (!enumerate-matches (match merged-pathname)
942       (let ((*ignore-wildcards* t)
943             (truename (truename (if (eq (sb!unix:unix-file-kind match)
944                                         :directory)
945                                     (concatenate 'string match "/")
946                                     match))))
947         (setf (gethash (namestring truename) truenames)
948               truename)))
949     (mapcar #'cdr
950             ;; Sorting isn't required by the ANSI spec, but sorting
951             ;; into some canonical order seems good just on the
952             ;; grounds that the implementation should have repeatable
953             ;; behavior when possible.
954             (sort (loop for name being each hash-key in truenames
955                         using (hash-value truename)
956                         collect (cons name truename))
957                   #'string<
958                   :key #'car))))
959 \f
960 ;;;; translating Unix uid's
961 ;;;;
962 ;;;; FIXME: should probably move into unix.lisp
963
964 (defvar *uid-hash-table* (make-hash-table)
965   #!+sb-doc
966   "hash table for keeping track of uid's and login names")
967
968 (/show0 "filesys.lisp 844")
969
970 ;;; LOOKUP-LOGIN-NAME translates a user id into a login name. Previous
971 ;;; lookups are cached in a hash table since groveling the passwd(s)
972 ;;; files is somewhat expensive. The table may hold NIL for id's that
973 ;;; cannot be looked up since this keeps the files from having to be
974 ;;; searched in their entirety each time this id is translated.
975 (defun lookup-login-name (uid)
976   (multiple-value-bind (login-name foundp) (gethash uid *uid-hash-table*)
977     (if foundp
978         login-name
979         (setf (gethash uid *uid-hash-table*)
980               (get-group-or-user-name :user uid)))))
981
982 ;;; GET-GROUP-OR-USER-NAME first tries "/etc/passwd" ("/etc/group")
983 ;;; since it is a much smaller file, contains all the local id's, and
984 ;;; most uses probably involve id's on machines one would login into.
985 ;;; Then if necessary, we look in "/etc/passwds" ("/etc/groups") which
986 ;;; is really long and has to be fetched over the net.
987 ;;;
988 ;;; FIXME: Now that we no longer have lookup-group-name, we no longer need
989 ;;; the GROUP-OR-USER argument.
990 (defun get-group-or-user-name (group-or-user id)
991   #!+sb-doc
992   "Returns the simple-string user or group name of the user whose uid or gid
993    is id, or NIL if no such user or group exists. Group-or-user is either
994    :group or :user."
995   (let ((id-string (let ((*print-base* 10)) (prin1-to-string id))))
996     (declare (simple-string id-string))
997     (multiple-value-bind (file1 file2)
998         (ecase group-or-user
999           (:group (values "/etc/group" "/etc/groups"))
1000           (:user (values "/etc/passwd" "/etc/passwd")))
1001       (or (get-group-or-user-name-aux id-string file1)
1002           (get-group-or-user-name-aux id-string file2)))))
1003
1004 ;;; FIXME: Isn't there now a POSIX routine to parse the passwd file?
1005 ;;; getpwent? getpwuid?
1006 (defun get-group-or-user-name-aux (id-string passwd-file)
1007   (with-open-file (stream passwd-file)
1008     (loop
1009       (let ((entry (read-line stream nil)))
1010         (unless entry (return nil))
1011         (let ((name-end (position #\: (the simple-string entry)
1012                                   :test #'char=)))
1013           (when name-end
1014             (let ((id-start (position #\: (the simple-string entry)
1015                                       :start (1+ name-end) :test #'char=)))
1016               (when id-start
1017                 (incf id-start)
1018                 (let ((id-end (position #\: (the simple-string entry)
1019                                         :start id-start :test #'char=)))
1020                   (when (and id-end
1021                              (string= id-string entry
1022                                       :start2 id-start :end2 id-end))
1023                     (return (subseq entry 0 name-end))))))))))))
1024 \f
1025 (/show0 "filesys.lisp 899")
1026
1027 ;;; predicate to order pathnames by; goes by name
1028 (defun pathname-order (x y)
1029   (let ((xn (%pathname-name x))
1030         (yn (%pathname-name y)))
1031     (if (and xn yn)
1032         (let ((res (string-lessp xn yn)))
1033           (cond ((not res) nil)
1034                 ((= res (length (the simple-string xn))) t)
1035                 ((= res (length (the simple-string yn))) nil)
1036                 (t t)))
1037         xn)))
1038 \f
1039 (defun ensure-directories-exist (pathspec &key verbose (mode #o777))
1040   #!+sb-doc
1041   "Test whether the directories containing the specified file
1042   actually exist, and attempt to create them if they do not.
1043   The MODE argument is a CMUCL/SBCL-specific extension to control
1044   the Unix permission bits."
1045   (let ((pathname (physicalize-pathname (pathname pathspec)))
1046         (created-p nil))
1047     (when (wild-pathname-p pathname)
1048       (error 'simple-file-error
1049              :format-control "bad place for a wild pathname"
1050              :pathname pathspec))
1051     (let ((dir (pathname-directory pathname)))
1052       (loop for i from 1 upto (length dir)
1053             do (let ((newpath (make-pathname
1054                                :host (pathname-host pathname)
1055                                :device (pathname-device pathname)
1056                                :directory (subseq dir 0 i))))
1057                  (unless (probe-file newpath)
1058                    (let ((namestring (namestring newpath)))
1059                      (when verbose
1060                        (format *standard-output*
1061                                "~&creating directory: ~A~%"
1062                                namestring))
1063                      (sb!unix:unix-mkdir namestring mode)
1064                      (unless (probe-file namestring)
1065                        (error 'simple-file-error
1066                               :pathname pathspec
1067                               :format-control "can't create directory ~A"
1068                               :format-arguments (list namestring)))
1069                      (setf created-p t)))))
1070       (values pathname created-p))))
1071
1072 (/show0 "filesys.lisp 1000")