Initial revision
[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
14 (file-comment
15   "$Header$")
16 \f
17 ;;;; Unix pathname host support
18
19 ;;; Unix namestrings have the following format:
20 ;;;
21 ;;; namestring := [ directory ] [ file [ type [ version ]]]
22 ;;; directory := [ "/" | search-list ] { file "/" }*
23 ;;; search-list := [^:/]*:
24 ;;; file := [^/]*
25 ;;; type := "." [^/.]*
26 ;;; version := "." ([0-9]+ | "*")
27 ;;;
28 ;;; FIXME: Search lists are no longer supported.
29 ;;;
30 ;;; Note: this grammar is ambiguous. The string foo.bar.5 can be
31 ;;; parsed as either just the file specified or as specifying the
32 ;;; file, type, and version. Therefore, we use the following rules
33 ;;; when confronted with an ambiguous file.type.version string:
34 ;;;
35 ;;; - If the first character is a dot, it's part of the file. It is not
36 ;;; considered a dot in the following rules.
37 ;;;
38 ;;; - If there is only one dot, it separates the file and the type.
39 ;;;
40 ;;; - If there are multiple dots and the stuff following the last dot
41 ;;; is a valid version, then that is the version and the stuff between
42 ;;; the second to last dot and the last dot is the type.
43 ;;;
44 ;;; Wildcard characters:
45 ;;;
46 ;;; If the directory, file, type components contain any of the
47 ;;; following characters, it is considered part of a wildcard pattern
48 ;;; and has the following meaning.
49 ;;;
50 ;;; ? - matches any character
51 ;;; * - matches any zero or more characters.
52 ;;; [abc] - matches any of a, b, or c.
53 ;;; {str1,str2,...,strn} - matches any of str1, str2, ..., or strn.
54 ;;;
55 ;;; Any of these special characters can be preceded by a backslash to
56 ;;; cause it to be treated as a regular character.
57 (defun remove-backslashes (namestr start end)
58   #!+sb-doc
59   "Remove any occurrences of #\\ from the string because we've already
60    checked for whatever they may have protected."
61   (declare (type simple-base-string namestr)
62            (type index start end))
63   (let* ((result (make-string (- end start)))
64          (dst 0)
65          (quoted nil))
66     (do ((src start (1+ src)))
67         ((= src end))
68       (cond (quoted
69              (setf (schar result dst) (schar namestr src))
70              (setf quoted nil)
71              (incf dst))
72             (t
73              (let ((char (schar namestr src)))
74                (cond ((char= char #\\)
75                       (setq quoted t))
76                      (t
77                       (setf (schar result dst) char)
78                       (incf dst)))))))
79     (when quoted
80       (error 'namestring-parse-error
81              :complaint "backslash in a bad place"
82              :namestring namestr
83              :offset (1- end)))
84     (shrink-vector result dst)))
85
86 (defvar *ignore-wildcards* nil)
87
88 (/show0 "filesys.lisp 86")
89
90 (defun maybe-make-pattern (namestr start end)
91   (declare (type simple-base-string namestr)
92            (type index start end))
93   (if *ignore-wildcards*
94       (subseq namestr start end)
95       (collect ((pattern))
96         (let ((quoted nil)
97               (any-quotes nil)
98               (last-regular-char nil)
99               (index start))
100           (flet ((flush-pending-regulars ()
101                    (when last-regular-char
102                      (pattern (if any-quotes
103                                   (remove-backslashes namestr
104                                                       last-regular-char
105                                                       index)
106                                   (subseq namestr last-regular-char index)))
107                      (setf any-quotes nil)
108                      (setf last-regular-char nil))))
109             (loop
110               (when (>= index end)
111                 (return))
112               (let ((char (schar namestr index)))
113                 (cond (quoted
114                        (incf index)
115                        (setf quoted nil))
116                       ((char= char #\\)
117                        (setf quoted t)
118                        (setf any-quotes t)
119                        (unless last-regular-char
120                          (setf last-regular-char index))
121                        (incf index))
122                       ((char= char #\?)
123                        (flush-pending-regulars)
124                        (pattern :single-char-wild)
125                        (incf index))
126                       ((char= char #\*)
127                        (flush-pending-regulars)
128                        (pattern :multi-char-wild)
129                        (incf index))
130                       ((char= char #\[)
131                        (flush-pending-regulars)
132                        (let ((close-bracket
133                               (position #\] namestr :start index :end end)))
134                          (unless close-bracket
135                            (error 'namestring-parse-error
136                                   :complaint "#\\[ with no corresponding #\\]"
137                                   :namestring namestr
138                                   :offset index))
139                          (pattern (list :character-set
140                                         (subseq namestr
141                                                 (1+ index)
142                                                 close-bracket)))
143                          (setf index (1+ close-bracket))))
144                       (t
145                        (unless last-regular-char
146                          (setf last-regular-char index))
147                        (incf index)))))
148             (flush-pending-regulars)))
149         (cond ((null (pattern))
150                "")
151               ((null (cdr (pattern)))
152                (let ((piece (first (pattern))))
153                  (typecase piece
154                    ((member :multi-char-wild) :wild)
155                    (simple-string piece)
156                    (t
157                     (make-pattern (pattern))))))
158               (t
159                (make-pattern (pattern)))))))
160
161 (/show0 "filesys.lisp 160")
162
163 (defun extract-name-type-and-version (namestr start end)
164   (declare (type simple-base-string namestr)
165            (type index start end))
166   (let* ((last-dot (position #\. namestr :start (1+ start) :end end
167                              :from-end t))
168          (second-to-last-dot (and last-dot
169                                   (position #\. namestr :start (1+ start)
170                                             :end last-dot :from-end t)))
171          (version :newest))
172     ;; If there is a second-to-last dot, check to see whether there is a valid
173     ;; version after the last dot.
174     (when second-to-last-dot
175       (cond ((and (= (+ last-dot 2) end)
176                   (char= (schar namestr (1+ last-dot)) #\*))
177              (setf version :wild))
178             ((and (< (1+ last-dot) end)
179                   (do ((index (1+ last-dot) (1+ index)))
180                       ((= index end) t)
181                     (unless (char<= #\0 (schar namestr index) #\9)
182                       (return nil))))
183              (setf version
184                    (parse-integer namestr :start (1+ last-dot) :end end)))
185             (t
186              (setf second-to-last-dot nil))))
187     (cond (second-to-last-dot
188            (values (maybe-make-pattern namestr start second-to-last-dot)
189                    (maybe-make-pattern namestr
190                                        (1+ second-to-last-dot)
191                                        last-dot)
192                    version))
193           (last-dot
194            (values (maybe-make-pattern namestr start last-dot)
195                    (maybe-make-pattern namestr (1+ last-dot) end)
196                    version))
197           (t
198            (values (maybe-make-pattern namestr start end)
199                    nil
200                    version)))))
201
202 (/show0 "filesys.lisp 200")
203
204 ;;; Take a string and return a list of cons cells that mark the char
205 ;;; separated subseq. The first value t if absolute directories location.
206 (defun split-at-slashes (namestr start end)
207   (declare (type simple-base-string namestr)
208            (type index start end))
209   (let ((absolute (and (/= start end)
210                        (char= (schar namestr start) #\/))))
211     (when absolute
212       (incf start))
213     ;; Next, split the remainder into slash-separated chunks.
214     (collect ((pieces))
215       (loop
216         (let ((slash (position #\/ namestr :start start :end end)))
217           (pieces (cons start (or slash end)))
218           (unless slash
219             (return))
220           (setf start (1+ slash))))
221       (values absolute (pieces)))))
222
223 (defun maybe-extract-search-list (namestr start end)
224   (declare (type simple-base-string namestr)
225            (type index start end))
226   (let ((quoted nil))
227     (do ((index start (1+ index)))
228         ((= index end)
229          (values nil start))
230       (if quoted
231           (setf quoted nil)
232           (case (schar namestr index)
233             (#\\
234              (setf quoted t))
235             (#\:
236              (return (values (remove-backslashes namestr start index)
237                              (1+ index)))))))))
238
239 (defun parse-unix-namestring (namestr start end)
240   (declare (type simple-base-string namestr)
241            (type index start end))
242   (multiple-value-bind (absolute pieces) (split-at-slashes namestr start end)
243     (let ((search-list (if absolute
244                            nil
245                            (let ((first (car pieces)))
246                              (multiple-value-bind (search-list new-start)
247                                  (maybe-extract-search-list namestr
248                                                             (car first)
249                                                             (cdr first))
250                                (when search-list
251                                  (setf absolute t)
252                                  (setf (car first) new-start))
253                                search-list)))))
254       (multiple-value-bind (name type version)
255           (let* ((tail (car (last pieces)))
256                  (tail-start (car tail))
257                  (tail-end (cdr tail)))
258             (unless (= tail-start tail-end)
259               (setf pieces (butlast pieces))
260               (extract-name-type-and-version namestr tail-start tail-end)))
261         ;; PVE: make sure there are no illegal characters in
262         ;; the name, illegal being (code-char 0) and #\/
263         #!+high-security
264         (when (and (stringp name)
265                    (find-if #'(lambda (x) (or (char= x (code-char 0))
266                                               (char= x #\/)))
267                             name))
268           (error 'parse-error))
269         
270         ;; Now we have everything we want. So return it.
271         (values nil ; no host for unix namestrings.
272                 nil ; no devices for unix namestrings.
273                 (collect ((dirs))
274                   (when search-list
275                     (dirs (intern-search-list search-list)))
276                   (dolist (piece pieces)
277                     (let ((piece-start (car piece))
278                           (piece-end (cdr piece)))
279                       (unless (= piece-start piece-end)
280                         (cond ((string= namestr ".." :start1 piece-start
281                                         :end1 piece-end)
282                                (dirs :up))
283                               ((string= namestr "**" :start1 piece-start
284                                         :end1 piece-end)
285                                (dirs :wild-inferiors))
286                               (t
287                                (dirs (maybe-make-pattern namestr
288                                                          piece-start
289                                                          piece-end)))))))
290                   (cond (absolute
291                          (cons :absolute (dirs)))
292                         ((dirs)
293                          (cons :relative (dirs)))
294                         (t
295                          nil)))
296                 name
297                 type
298                 version)))))
299
300 (/show0 "filesys.lisp 300")
301
302 (defun unparse-unix-host (pathname)
303   (declare (type pathname pathname)
304            (ignore pathname))
305   "Unix")
306
307 (defun unparse-unix-piece (thing)
308   (etypecase thing
309     ((member :wild) "*")
310     (simple-string
311      (let* ((srclen (length thing))
312             (dstlen srclen))
313        (dotimes (i srclen)
314          (case (schar thing i)
315            ((#\* #\? #\[)
316             (incf dstlen))))
317        (let ((result (make-string dstlen))
318              (dst 0))
319          (dotimes (src srclen)
320            (let ((char (schar thing src)))
321              (case char
322                ((#\* #\? #\[)
323                 (setf (schar result dst) #\\)
324                 (incf dst)))
325              (setf (schar result dst) char)
326              (incf dst)))
327          result)))
328     (pattern
329      (collect ((strings))
330        (dolist (piece (pattern-pieces thing))
331          (etypecase piece
332            (simple-string
333             (strings piece))
334            (symbol
335             (ecase piece
336               (:multi-char-wild
337                (strings "*"))
338               (:single-char-wild
339                (strings "?"))))
340            (cons
341             (case (car piece)
342               (:character-set
343                (strings "[")
344                (strings (cdr piece))
345                (strings "]"))
346               (t
347                (error "invalid pattern piece: ~S" piece))))))
348        (apply #'concatenate
349               'simple-string
350               (strings))))))
351
352 (defun unparse-unix-directory-list (directory)
353   (declare (type list directory))
354   (collect ((pieces))
355     (when directory
356       (ecase (pop directory)
357         (:absolute
358          (cond ((search-list-p (car directory))
359                 (pieces (search-list-name (pop directory)))
360                 (pieces ":"))
361                (t
362                 (pieces "/"))))
363         (:relative
364          ;; Nothing special.
365          ))
366       (dolist (dir directory)
367         (typecase dir
368           ((member :up)
369            (pieces "../"))
370           ((member :back)
371            (error ":BACK cannot be represented in namestrings."))
372           ((member :wild-inferiors)
373            (pieces "**/"))
374           ((or simple-string pattern)
375            (pieces (unparse-unix-piece dir))
376            (pieces "/"))
377           (t
378            (error "invalid directory component: ~S" dir)))))
379     (apply #'concatenate 'simple-string (pieces))))
380
381 (defun unparse-unix-directory (pathname)
382   (declare (type pathname pathname))
383   (unparse-unix-directory-list (%pathname-directory pathname)))
384
385 (defun unparse-unix-file (pathname)
386   (declare (type pathname pathname))
387   (collect ((strings))
388     (let* ((name (%pathname-name pathname))
389            (type (%pathname-type pathname))
390            (type-supplied (not (or (null type) (eq type :unspecific))))
391            (version (%pathname-version pathname))
392            (version-supplied (not (or (null version) (eq version :newest)))))
393       (when name
394         (strings (unparse-unix-piece name)))
395       (when type-supplied
396         (unless name
397           (error "cannot specify the type without a file: ~S" pathname))
398         (strings ".")
399         (strings (unparse-unix-piece type)))
400       (when version-supplied
401         (unless type-supplied
402           (error "cannot specify the version without a type: ~S" pathname))
403         (strings (if (eq version :wild)
404                      ".*"
405                      (format nil ".~D" version)))))
406     (apply #'concatenate 'simple-string (strings))))
407
408 (/show0 "filesys.lisp 406")
409
410 (defun unparse-unix-namestring (pathname)
411   (declare (type pathname pathname))
412   (concatenate 'simple-string
413                (unparse-unix-directory pathname)
414                (unparse-unix-file pathname)))
415
416 (defun unparse-unix-enough (pathname defaults)
417   (declare (type pathname pathname defaults))
418   (flet ((lose ()
419            (error "~S cannot be represented relative to ~S."
420                   pathname defaults)))
421     (collect ((strings))
422       (let* ((pathname-directory (%pathname-directory pathname))
423              (defaults-directory (%pathname-directory defaults))
424              (prefix-len (length defaults-directory))
425              (result-dir
426               (cond ((and (> prefix-len 1)
427                           (>= (length pathname-directory) prefix-len)
428                           (compare-component (subseq pathname-directory
429                                                      0 prefix-len)
430                                              defaults-directory))
431                      ;; Pathname starts with a prefix of default. So
432                      ;; just use a relative directory from then on out.
433                      (cons :relative (nthcdr prefix-len pathname-directory)))
434                     ((eq (car pathname-directory) :absolute)
435                      ;; We are an absolute pathname, so we can just use it.
436                      pathname-directory)
437                     (t
438                      ;; We are a relative directory. So we lose.
439                      (lose)))))
440         (strings (unparse-unix-directory-list result-dir)))
441       (let* ((pathname-version (%pathname-version pathname))
442              (version-needed (and pathname-version
443                                   (not (eq pathname-version :newest))))
444              (pathname-type (%pathname-type pathname))
445              (type-needed (or version-needed
446                               (and pathname-type
447                                    (not (eq pathname-type :unspecific)))))
448              (pathname-name (%pathname-name pathname))
449              (name-needed (or type-needed
450                               (and pathname-name
451                                    (not (compare-component pathname-name
452                                                            (%pathname-name
453                                                             defaults)))))))
454         (when name-needed
455           (unless pathname-name (lose))
456           (strings (unparse-unix-piece pathname-name)))
457         (when type-needed
458           (when (or (null pathname-type) (eq pathname-type :unspecific))
459             (lose))
460           (strings ".")
461           (strings (unparse-unix-piece pathname-type)))
462         (when version-needed
463           (typecase pathname-version
464             ((member :wild)
465              (strings ".*"))
466             (integer
467              (strings (format nil ".~D" pathname-version)))
468             (t
469              (lose)))))
470       (apply #'concatenate 'simple-string (strings)))))
471
472 (/show0 "filesys.lisp 471")
473
474 (def!struct (unix-host
475              (:make-load-form-fun make-unix-host-load-form)
476              (:include host
477                        (parse #'parse-unix-namestring)
478                        (unparse #'unparse-unix-namestring)
479                        (unparse-host #'unparse-unix-host)
480                        (unparse-directory #'unparse-unix-directory)
481                        (unparse-file #'unparse-unix-file)
482                        (unparse-enough #'unparse-unix-enough)
483                        (customary-case :lower))))
484
485 (/show0 "filesys.lisp 486")
486
487 (defvar *unix-host* (make-unix-host))
488
489 (/show0 "filesys.lisp 488")
490
491 (defun make-unix-host-load-form (host)
492   (declare (ignore host))
493   '*unix-host*)
494 \f
495 ;;;; wildcard matching stuff
496
497 (/show0 "filesys.lisp 498")
498
499 ;;; FIXME: could maybe be EVAL-WHEN (COMPILE EVAL)
500 (defmacro enumerate-matches ((var pathname &optional result
501                                   &key (verify-existence t))
502                              &body body)
503   (let ((body-name (gensym)))
504     `(block nil
505        (flet ((,body-name (,var)
506                 ,@body))
507          (%enumerate-matches (pathname ,pathname)
508                              ,verify-existence
509                              #',body-name)
510          ,result))))
511
512 (/show0 "filesys.lisp 500")
513
514 (defun %enumerate-matches (pathname verify-existence function)
515   (/show0 "entering %ENUMERATE-MATCHES")
516   (when (pathname-type pathname)
517     (unless (pathname-name pathname)
518       (error "cannot supply a type without a name:~%  ~S" pathname)))
519   (when (and (integerp (pathname-version pathname))
520              (member (pathname-type pathname) '(nil :unspecific)))
521     (error "cannot supply a version without a type:~%  ~S" pathname))
522   (let ((directory (pathname-directory pathname)))
523     (/show0 "computed DIRECTORY")
524     (if directory
525         (ecase (car directory)
526           (:absolute
527            (/show0 "absolute directory")
528            (%enumerate-directories "/" (cdr directory) pathname
529                                    verify-existence function))
530           (:relative
531            (/show0 "relative directory")
532            (%enumerate-directories "" (cdr directory) pathname
533                                    verify-existence function)))
534         (%enumerate-files "" pathname verify-existence function))))
535
536 (defun %enumerate-directories (head tail pathname verify-existence function)
537   (declare (simple-string head))
538   (if tail
539       (let ((piece (car tail)))
540         (etypecase piece
541           (simple-string
542            (%enumerate-directories (concatenate 'string head piece "/")
543                                    (cdr tail) pathname verify-existence
544                                    function))
545           ((or pattern (member :wild :wild-inferiors))
546            (let ((dir (sb!unix:open-dir head)))
547              (when dir
548                (unwind-protect
549                    (loop
550                      (let ((name (sb!unix:read-dir dir)))
551                        (cond ((null name)
552                               (return))
553                              ((string= name "."))
554                              ((string= name ".."))
555                              ((pattern-matches piece name)
556                               (let ((subdir (concatenate 'string
557                                                          head name "/")))
558                                 (when (eq (sb!unix:unix-file-kind subdir)
559                                           :directory)
560                                   (%enumerate-directories
561                                    subdir (cdr tail) pathname verify-existence
562                                    function)))))))
563                  (sb!unix:close-dir dir)))))
564           ((member :up)
565            (%enumerate-directories (concatenate 'string head "../")
566                                    (cdr tail) pathname verify-existence
567                                    function))))
568       (%enumerate-files head pathname verify-existence function)))
569
570 ;;; REMOVEME after finding bug.
571 #!+sb-show (defvar *show-directory*)
572 #!+sb-show (defvar *show-name*)
573
574 (defun %enumerate-files (directory pathname verify-existence function)
575   (declare (simple-string directory))
576   (/show0 "entering %ENUMERATE-FILES")
577   (let ((name (%pathname-name pathname))
578         (type (%pathname-type pathname))
579         (version (%pathname-version pathname)))
580     (/show0 "computed NAME, TYPE, and VERSION")
581     (cond ((member name '(nil :unspecific))
582            (/show0 "UNSPECIFIC, more or less")
583            (when (or (not verify-existence)
584                      (sb!unix:unix-file-kind directory))
585              (funcall function directory)))
586           ((or (pattern-p name)
587                (pattern-p type)
588                (eq name :wild)
589                (eq type :wild))
590            (/show0 "WILD, more or less")
591            (let ((dir (sb!unix:open-dir directory)))
592              (when dir
593                (unwind-protect
594                    (loop
595                      (/show0 "at head of LOOP")
596                      (let ((file (sb!unix:read-dir dir)))
597                        (if file
598                            (unless (or (string= file ".")
599                                        (string= file ".."))
600                              (multiple-value-bind
601                                  (file-name file-type file-version)
602                                  (let ((*ignore-wildcards* t))
603                                    (extract-name-type-and-version
604                                     file 0 (length file)))
605                                (when (and (components-match file-name name)
606                                           (components-match file-type type)
607                                           (components-match file-version
608                                                             version))
609                                  (funcall function
610                                           (concatenate 'string
611                                                        directory
612                                                        file)))))
613                            (return))))
614                  (sb!unix:close-dir dir)))))
615           (t
616            (/show0 "default case")
617            
618            ;; Put DIRECTORY and NAME somewhere we can find them even when
619            ;; things are too screwed up for the debugger.
620            #!+sb-show (progn
621                         (setf *show-directory* directory
622                               *show-name* name))
623
624            (let ((file (concatenate 'string directory name)))
625              (/show0 "computed basic FILE=..")
626              #!+sb-show (%primitive print file)
627              (unless (or (null type) (eq type :unspecific))
628                (/show0 "tweaking FILE for more-or-less-:UNSPECIFIC case")
629                (setf file (concatenate 'string file "." type)))
630              (unless (member version '(nil :newest :wild))
631                (/show0 "tweaking FILE for more-or-less-:WILD case")
632                (setf file (concatenate 'string file "."
633                                        (quick-integer-to-string version))))
634              (/show0 "finished possibly tweaking FILE=..")
635              #!+sb-show (%primitive print file)
636              (when (or (not verify-existence)
637                        (sb!unix:unix-file-kind file t))
638                (/show0 "calling FUNCTION on FILE")
639                (funcall function file)))))))
640
641 (/show0 "filesys.lisp 603")
642
643 ;;; FIXME: Why do we need this?
644 (defun quick-integer-to-string (n)
645   (declare (type integer n))
646   (cond ((not (fixnump n))
647          (write-to-string n :base 10 :radix nil))
648         ((zerop n) "0")
649         ((eql n 1) "1")
650         ((minusp n)
651          (concatenate 'simple-string "-"
652                       (the simple-string (quick-integer-to-string (- n)))))
653         (t
654          (do* ((len (1+ (truncate (integer-length n) 3)))
655                (res (make-string len))
656                (i (1- len) (1- i))
657                (q n)
658                (r 0))
659               ((zerop q)
660                (incf i)
661                (replace res res :start2 i :end2 len)
662                (shrink-vector res (- len i)))
663            (declare (simple-string res)
664                     (fixnum len i r q))
665            (multiple-value-setq (q r) (truncate q 10))
666            (setf (schar res i) (schar "0123456789" r))))))
667 \f
668 ;;;; UNIX-NAMESTRING
669
670 (defun unix-namestring (pathname &optional (for-input t) executable-only)
671   #!+sb-doc
672   "Convert PATHNAME into a string that can be used with UNIX system calls.
673    Search-lists and wild-cards are expanded."
674   ;; toy@rtp.ericsson.se: Let unix-namestring also handle logical
675   ;; pathnames too.
676   ;; FIXME: What does this ^ mean? A bug? A remark on a change already made?
677   (/show0 "entering UNIX-NAMESTRING")
678   (let ((path (let ((lpn (pathname pathname)))
679                 (if (typep lpn 'logical-pathname)
680                     (namestring (translate-logical-pathname lpn))
681                     pathname))))
682     (/show0 "PATH computed, enumerating search list")
683     (enumerate-search-list
684       (pathname path)
685       (collect ((names))
686         (/show0 "collecting NAMES")
687         (enumerate-matches (name pathname nil :verify-existence for-input)
688                            (when (or (not executable-only)
689                                      (and (eq (sb!unix:unix-file-kind name)
690                                               :file)
691                                           (sb!unix:unix-access name
692                                                                sb!unix:x_ok)))
693                              (names name)))
694         (/show0 "NAMES collected")
695         (let ((names (names)))
696           (when names
697             (/show0 "NAMES is true.")
698             (when (cdr names)
699               (/show0 "Alas! CDR NAMES")
700               (error 'simple-file-error
701                      :format-control "~S is ambiguous:~{~%  ~A~}"
702                      :format-arguments (list pathname names)))
703             (/show0 "returning from UNIX-NAMESTRING")
704             (return (car names))))))))
705 \f
706 ;;;; TRUENAME and PROBE-FILE
707
708 ;;; Another silly file function trivially different from another function.
709 (defun truename (pathname)
710   #!+sb-doc
711   "Return the pathname for the actual file described by the pathname
712   An error of type file-error is signalled if no such file exists,
713   or the pathname is wild."
714   (if (wild-pathname-p pathname)
715       (error 'simple-file-error
716              :format-control "bad place for a wild pathname"
717              :pathname pathname)
718       (let ((result (probe-file pathname)))
719         (unless result
720           (error 'simple-file-error
721                  :pathname pathname
722                  :format-control "The file ~S does not exist."
723                  :format-arguments (list (namestring pathname))))
724         result)))
725
726 ;;; If PATHNAME exists, return its truename, otherwise NIL.
727 (defun probe-file (pathname)
728   #!+sb-doc
729   "Return a pathname which is the truename of the file if it exists, NIL
730   otherwise. An error of type file-error is signaled if pathname is wild."
731   (/show0 "entering PROBE-FILE")
732   (if (wild-pathname-p pathname)
733       (error 'simple-file-error
734              :pathname pathname
735              :format-control "bad place for a wild pathname")
736       (let ((namestring (unix-namestring pathname t)))
737         (/show0 "NAMESTRING computed")
738         (when (and namestring (sb!unix:unix-file-kind namestring))
739           (/show0 "NAMESTRING is promising.")
740           (let ((truename (sb!unix:unix-resolve-links
741                            (sb!unix:unix-maybe-prepend-current-directory
742                             namestring))))
743             (/show0 "TRUENAME computed")
744             (when truename
745               (/show0 "TRUENAME is true.")
746               (let ((*ignore-wildcards* t))
747                 (pathname (sb!unix:unix-simplify-pathname truename)))))))))
748 \f
749 ;;;; miscellaneous other operations
750
751 (/show0 "filesys.lisp 700")
752
753 (defun rename-file (file new-name)
754   #!+sb-doc
755   "Rename File to have the specified New-Name. If file is a stream open to a
756   file, then the associated file is renamed."
757   (let* ((original (truename file))
758          (original-namestring (unix-namestring original t))
759          (new-name (merge-pathnames new-name original))
760          (new-namestring (unix-namestring new-name nil)))
761     (unless new-namestring
762       (error 'simple-file-error
763              :pathname new-name
764              :format-control "~S can't be created."
765              :format-arguments (list new-name)))
766     (multiple-value-bind (res error)
767         (sb!unix:unix-rename original-namestring new-namestring)
768       (unless res
769         (error 'simple-file-error
770                :pathname new-name
771                :format-control "failed to rename ~A to ~A: ~A"
772                :format-arguments (list original new-name
773                                        (sb!unix:get-unix-error-msg error))))
774       (when (streamp file)
775         (file-name file new-namestring))
776       (values new-name original (truename new-name)))))
777
778 (defun delete-file (file)
779   #!+sb-doc
780   "Delete the specified file."
781   (let ((namestring (unix-namestring file t)))
782     (when (streamp file)
783       (close file :abort t))
784     (unless namestring
785       (error 'simple-file-error
786              :pathname file
787              :format-control "~S doesn't exist."
788              :format-arguments (list file)))
789
790     (multiple-value-bind (res err) (sb!unix:unix-unlink namestring)
791       (unless res
792         (error 'simple-file-error
793                :pathname namestring
794                :format-control "could not delete ~A: ~A"
795                :format-arguments (list namestring
796                                        (sb!unix:get-unix-error-msg err))))))
797   t)
798 \f
799 ;;; Return Home:, which is set up for us at initialization time.
800 (defun user-homedir-pathname (&optional host)
801   #!+sb-doc
802   "Returns the home directory of the logged in user as a pathname.
803   This is obtained from the logical name \"home:\"."
804   (declare (ignore host))
805   ;; Note: CMU CL did #P"home:" here instead of using a call to
806   ;; PATHNAME. Delaying construction of the pathname until we're
807   ;; running in a target Lisp lets us avoid figuring out how to dump
808   ;; cross-compilation host Lisp PATHNAME objects into a target Lisp
809   ;; object file. It also might have a small positive effect on
810   ;; efficiency, in that we don't allocate a PATHNAME we don't need,
811   ;; but it it could also have a larger negative effect. Hopefully
812   ;; it'll be OK. -- WHN 19990714
813   (pathname "home:"))
814
815 (defun file-write-date (file)
816   #!+sb-doc
817   "Return file's creation date, or NIL if it doesn't exist.
818  An error of type file-error is signaled if file is a wild pathname"
819   (if (wild-pathname-p file)
820       ;; FIXME: This idiom appears many times in this file. Perhaps it
821       ;; should turn into (CANNOT-BE-WILD-PATHNAME FILE). (C-B-W-P
822       ;; should be a macro, not a function, so that the error message
823       ;; is reported as coming from e.g. FILE-WRITE-DATE instead of
824       ;; from CANNOT-BE-WILD-PATHNAME itself.)
825       (error 'simple-file-error
826              :pathname file
827              :format-control "bad place for a wild pathname")
828       (let ((name (unix-namestring file t)))
829         (when name
830           (multiple-value-bind
831               (res dev ino mode nlink uid gid rdev size atime mtime)
832               (sb!unix:unix-stat name)
833             (declare (ignore dev ino mode nlink uid gid rdev size atime))
834             (when res
835               (+ unix-to-universal-time mtime)))))))
836
837 (defun file-author (file)
838   #!+sb-doc
839   "Returns the file author as a string, or nil if the author cannot be
840  determined. Signals an error of type file-error if file doesn't exist,
841  or file is a wild pathname."
842   (if (wild-pathname-p file)
843       (error 'simple-file-error
844              :pathname file
845              "bad place for a wild pathname")
846       (let ((name (unix-namestring (pathname file) t)))
847         (unless name
848           (error 'simple-file-error
849                  :pathname file
850                  :format-control "~S doesn't exist."
851                  :format-arguments (list file)))
852         (multiple-value-bind (winp dev ino mode nlink uid)
853             (sb!unix:unix-stat name)
854           (declare (ignore dev ino mode nlink))
855           (if winp (lookup-login-name uid))))))
856 \f
857 ;;;; DIRECTORY
858
859 (/show0 "filesys.lisp 800")
860
861 (defun directory (pathname &key (all t) (check-for-subdirs t)
862                            (follow-links t))
863   #!+sb-doc
864   "Returns a list of pathnames, one for each file that matches the given
865    pathname. Supplying :ALL as nil causes this to ignore Unix dot files. This
866    never includes Unix dot and dot-dot in the result. If :FOLLOW-LINKS is NIL,
867    then symblolic links in the result are not expanded. This is not the
868    default because TRUENAME does follow links, and the result pathnames are
869    defined to be the TRUENAME of the pathname (the truename of a link may well
870    be in another directory.)"
871   (let ((results nil))
872     (enumerate-search-list
873         (pathname (merge-pathnames pathname
874                                    (make-pathname :name :wild
875                                                   :type :wild
876                                                   :version :wild)))
877       (enumerate-matches (name pathname)
878         (when (or all
879                   (let ((slash (position #\/ name :from-end t)))
880                     (or (null slash)
881                         (= (1+ slash) (length name))
882                         (char/= (schar name (1+ slash)) #\.))))
883           (push name results))))
884     (let ((*ignore-wildcards* t))
885       (mapcar #'(lambda (name)
886                   (let ((name (if (and check-for-subdirs
887                                        (eq (sb!unix:unix-file-kind name)
888                                            :directory))
889                                   (concatenate 'string name "/")
890                                   name)))
891                     (if follow-links (truename name) (pathname name))))
892               (sort (delete-duplicates results :test #'string=) #'string<)))))
893 \f
894 ;;;; translating Unix uid's
895 ;;;;
896 ;;;; FIXME: should probably move into unix.lisp
897
898 (defvar *uid-hash-table* (make-hash-table)
899   #!+sb-doc
900   "hash table for keeping track of uid's and login names")
901
902 (/show0 "filesys.lisp 844")
903
904 ;;; LOOKUP-LOGIN-NAME translates a user id into a login name. Previous
905 ;;; lookups are cached in a hash table since groveling the passwd(s)
906 ;;; files is somewhat expensive. The table may hold NIL for id's that
907 ;;; cannot be looked up since this keeps the files from having to be
908 ;;; searched in their entirety each time this id is translated.
909 (defun lookup-login-name (uid)
910   (multiple-value-bind (login-name foundp) (gethash uid *uid-hash-table*)
911     (if foundp
912         login-name
913         (setf (gethash uid *uid-hash-table*)
914               (get-group-or-user-name :user uid)))))
915
916 ;;; GET-GROUP-OR-USER-NAME first tries "/etc/passwd" ("/etc/group")
917 ;;; since it is a much smaller file, contains all the local id's, and
918 ;;; most uses probably involve id's on machines one would login into.
919 ;;; Then if necessary, we look in "/etc/passwds" ("/etc/groups") which
920 ;;; is really long and has to be fetched over the net.
921 ;;;
922 ;;; FIXME: Now that we no longer have lookup-group-name, we no longer need
923 ;;; the GROUP-OR-USER argument.
924 (defun get-group-or-user-name (group-or-user id)
925   #!+sb-doc
926   "Returns the simple-string user or group name of the user whose uid or gid
927    is id, or NIL if no such user or group exists. Group-or-user is either
928    :group or :user."
929   (let ((id-string (let ((*print-base* 10)) (prin1-to-string id))))
930     (declare (simple-string id-string))
931     (multiple-value-bind (file1 file2)
932         (ecase group-or-user
933           (:group (values "/etc/group" "/etc/groups"))
934           (:user (values "/etc/passwd" "/etc/passwd")))
935       (or (get-group-or-user-name-aux id-string file1)
936           (get-group-or-user-name-aux id-string file2)))))
937
938 ;;; FIXME: Isn't there now a POSIX routine to parse the passwd file?
939 ;;; getpwent? getpwuid?
940 (defun get-group-or-user-name-aux (id-string passwd-file)
941   (with-open-file (stream passwd-file)
942     (loop
943       (let ((entry (read-line stream nil)))
944         (unless entry (return nil))
945         (let ((name-end (position #\: (the simple-string entry)
946                                   :test #'char=)))
947           (when name-end
948             (let ((id-start (position #\: (the simple-string entry)
949                                       :start (1+ name-end) :test #'char=)))
950               (when id-start
951                 (incf id-start)
952                 (let ((id-end (position #\: (the simple-string entry)
953                                         :start id-start :test #'char=)))
954                   (when (and id-end
955                              (string= id-string entry
956                                       :start2 id-start :end2 id-end))
957                     (return (subseq entry 0 name-end))))))))))))
958 \f
959 (/show0 "filesys.lisp 899")
960
961 ;;; Predicate to order pathnames by. Goes by name.
962 (defun pathname-order (x y)
963   (let ((xn (%pathname-name x))
964         (yn (%pathname-name y)))
965     (if (and xn yn)
966         (let ((res (string-lessp xn yn)))
967           (cond ((not res) nil)
968                 ((= res (length (the simple-string xn))) t)
969                 ((= res (length (the simple-string yn))) nil)
970                 (t t)))
971         xn)))
972 \f
973 (defun default-directory ()
974   #!+sb-doc
975   "Returns the pathname for the default directory. This is the place where
976   a file will be written if no directory is specified. This may be changed
977   with setf."
978   (multiple-value-bind (gr dir-or-error) (sb!unix:unix-current-directory)
979     (if gr
980         (let ((*ignore-wildcards* t))
981           (pathname (concatenate 'simple-string dir-or-error "/")))
982         (error dir-or-error))))
983
984 (defun %set-default-directory (new-val)
985   (let ((namestring (unix-namestring new-val t)))
986     (unless namestring
987       (error "~S doesn't exist." new-val))
988     (multiple-value-bind (gr error) (sb!unix:unix-chdir namestring)
989       (if gr
990           (setf (search-list "default:") (default-directory))
991           (error (sb!unix:get-unix-error-msg error))))
992     new-val))
993
994 (/show0 "filesys.lisp 934")
995
996 (defun !filesys-cold-init ()
997   (/show0 "entering !FILESYS-COLD-INIT")
998   (setf *default-pathname-defaults*
999         (%make-pathname *unix-host* nil nil nil nil :newest))
1000   (setf (search-list "default:") (default-directory))
1001   (/show0 "leaving !FILESYS-COLD-INIT")
1002   nil)
1003 \f
1004 (defun ensure-directories-exist (pathspec &key verbose (mode #o777))
1005   #!+sb-doc
1006   "Tests whether the directories containing the specified file
1007   actually exist, and attempts to create them if they do not.
1008   Portable programs should avoid using the :MODE keyword argument."
1009   (let* ((pathname (pathname pathspec))
1010          (pathname (if (typep pathname 'logical-pathname)
1011                        (translate-logical-pathname pathname)
1012                        pathname))
1013          (created-p nil))
1014     (when (wild-pathname-p pathname)
1015       (error 'simple-file-error
1016              :format-control "bad place for a wild pathname"
1017              :pathname pathspec))
1018     (enumerate-search-list (pathname pathname)
1019        (let ((dir (pathname-directory pathname)))
1020          (loop for i from 1 upto (length dir)
1021                do (let ((newpath (make-pathname
1022                                   :host (pathname-host pathname)
1023                                   :device (pathname-device pathname)
1024                                   :directory (subseq dir 0 i))))
1025                     (unless (probe-file newpath)
1026                       (let ((namestring (namestring newpath)))
1027                         (when verbose
1028                           (format *standard-output*
1029                                   "~&creating directory: ~A~%"
1030                                   namestring))
1031                         (sb!unix:unix-mkdir namestring mode)
1032                         (unless (probe-file namestring)
1033                           (error 'simple-file-error
1034                                  :pathname pathspec
1035                                  :format-control "can't create directory ~A"
1036                                  :format-arguments (list namestring)))
1037                         (setf created-p t)))))
1038          ;; Only the first path in a search-list is considered.
1039          (return (values pathname created-p))))))
1040
1041 (/show0 "filesys.lisp 1000")