added various /SHOW0-ish statements to help when debugging internal
[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 (defun %enumerate-files (directory pathname verify-existence function)
571   (declare (simple-string directory))
572   (/show0 "entering %ENUMERATE-FILES")
573   (let ((name (%pathname-name pathname))
574         (type (%pathname-type pathname))
575         (version (%pathname-version pathname)))
576     (/show0 "computed NAME, TYPE, and VERSION")
577     (cond ((member name '(nil :unspecific))
578            (/show0 "UNSPECIFIC, more or less")
579            (when (or (not verify-existence)
580                      (sb!unix:unix-file-kind directory))
581              (funcall function directory)))
582           ((or (pattern-p name)
583                (pattern-p type)
584                (eq name :wild)
585                (eq type :wild))
586            (/show0 "WILD, more or less")
587            (let ((dir (sb!unix:open-dir directory)))
588              (when dir
589                (unwind-protect
590                    (loop
591                      (/show0 "at head of LOOP")
592                      (let ((file (sb!unix:read-dir dir)))
593                        (if file
594                            (unless (or (string= file ".")
595                                        (string= file ".."))
596                              (multiple-value-bind
597                                  (file-name file-type file-version)
598                                  (let ((*ignore-wildcards* t))
599                                    (extract-name-type-and-version
600                                     file 0 (length file)))
601                                (when (and (components-match file-name name)
602                                           (components-match file-type type)
603                                           (components-match file-version
604                                                             version))
605                                  (funcall function
606                                           (concatenate 'string
607                                                        directory
608                                                        file)))))
609                            (return))))
610                  (sb!unix:close-dir dir)))))
611           (t
612            (/show0 "default case")
613            (let ((file (concatenate 'string directory name)))
614              (/show0 "computed basic FILE=..")
615              #!+sb-show (%primitive print file)
616              (unless (or (null type) (eq type :unspecific))
617                (/show0 "tweaking FILE for more-or-less-:UNSPECIFIC case")
618                (setf file (concatenate 'string file "." type)))
619              (unless (member version '(nil :newest :wild))
620                (/show0 "tweaking FILE for more-or-less-:WILD case")
621                (setf file (concatenate 'string file "."
622                                        (quick-integer-to-string version))))
623              (/show0 "finished possibly tweaking FILE=..")
624              #!+sb-show (%primitive print file)
625              (when (or (not verify-existence)
626                        (sb!unix:unix-file-kind file t))
627                (/show0 "calling FUNCTION on FILE")
628                (funcall function file)))))))
629
630 (/show0 "filesys.lisp 603")
631
632 ;;; FIXME: Why do we need this?
633 (defun quick-integer-to-string (n)
634   (declare (type integer n))
635   (cond ((not (fixnump n))
636          (write-to-string n :base 10 :radix nil))
637         ((zerop n) "0")
638         ((eql n 1) "1")
639         ((minusp n)
640          (concatenate 'simple-string "-"
641                       (the simple-string (quick-integer-to-string (- n)))))
642         (t
643          (do* ((len (1+ (truncate (integer-length n) 3)))
644                (res (make-string len))
645                (i (1- len) (1- i))
646                (q n)
647                (r 0))
648               ((zerop q)
649                (incf i)
650                (replace res res :start2 i :end2 len)
651                (shrink-vector res (- len i)))
652            (declare (simple-string res)
653                     (fixnum len i r q))
654            (multiple-value-setq (q r) (truncate q 10))
655            (setf (schar res i) (schar "0123456789" r))))))
656 \f
657 ;;;; UNIX-NAMESTRING
658
659 (defun unix-namestring (pathname &optional (for-input t) executable-only)
660   #!+sb-doc
661   "Convert PATHNAME into a string that can be used with UNIX system calls.
662    Search-lists and wild-cards are expanded."
663   ;; toy@rtp.ericsson.se: Let unix-namestring also handle logical
664   ;; pathnames too.
665   ;; FIXME: What does this ^ mean? A bug? A remark on a change already made?
666   (/show0 "entering UNIX-NAMESTRING")
667   (let ((path (let ((lpn (pathname pathname)))
668                 (if (typep lpn 'logical-pathname)
669                     (namestring (translate-logical-pathname lpn))
670                     pathname))))
671     (/show0 "PATH computed, enumerating search list")
672     (enumerate-search-list
673       (pathname path)
674       (collect ((names))
675         (/show0 "collecting NAMES")
676         (enumerate-matches (name pathname nil :verify-existence for-input)
677                            (when (or (not executable-only)
678                                      (and (eq (sb!unix:unix-file-kind name)
679                                               :file)
680                                           (sb!unix:unix-access name
681                                                                sb!unix:x_ok)))
682                              (names name)))
683         (/show0 "NAMES collected")
684         (let ((names (names)))
685           (when names
686             (/show0 "NAMES is true.")
687             (when (cdr names)
688               (/show0 "Alas! CDR NAMES")
689               (error 'simple-file-error
690                      :format-control "~S is ambiguous:~{~%  ~A~}"
691                      :format-arguments (list pathname names)))
692             (/show0 "returning from UNIX-NAMESTRING")
693             (return (car names))))))))
694 \f
695 ;;;; TRUENAME and PROBE-FILE
696
697 ;;; Another silly file function trivially different from another function.
698 (defun truename (pathname)
699   #!+sb-doc
700   "Return the pathname for the actual file described by the pathname
701   An error of type file-error is signalled if no such file exists,
702   or the pathname is wild."
703   (if (wild-pathname-p pathname)
704       (error 'simple-file-error
705              :format-control "bad place for a wild pathname"
706              :pathname pathname)
707       (let ((result (probe-file pathname)))
708         (unless result
709           (error 'simple-file-error
710                  :pathname pathname
711                  :format-control "The file ~S does not exist."
712                  :format-arguments (list (namestring pathname))))
713         result)))
714
715 ;;; If PATHNAME exists, return its truename, otherwise NIL.
716 (defun probe-file (pathname)
717   #!+sb-doc
718   "Return a pathname which is the truename of the file if it exists, NIL
719   otherwise. An error of type file-error is signaled if pathname is wild."
720   (/show0 "entering PROBE-FILE")
721   (if (wild-pathname-p pathname)
722       (error 'simple-file-error
723              :pathname pathname
724              :format-control "bad place for a wild pathname")
725       (let ((namestring (unix-namestring pathname t)))
726         (/show0 "NAMESTRING computed")
727         (when (and namestring (sb!unix:unix-file-kind namestring))
728           (/show0 "NAMESTRING is promising.")
729           (let ((truename (sb!unix:unix-resolve-links
730                            (sb!unix:unix-maybe-prepend-current-directory
731                             namestring))))
732             (/show0 "TRUENAME computed")
733             (when truename
734               (/show0 "TRUENAME is true.")
735               (let ((*ignore-wildcards* t))
736                 (pathname (sb!unix:unix-simplify-pathname truename)))))))))
737 \f
738 ;;;; miscellaneous other operations
739
740 (/show0 "filesys.lisp 700")
741
742 (defun rename-file (file new-name)
743   #!+sb-doc
744   "Rename File to have the specified New-Name. If file is a stream open to a
745   file, then the associated file is renamed."
746   (let* ((original (truename file))
747          (original-namestring (unix-namestring original t))
748          (new-name (merge-pathnames new-name original))
749          (new-namestring (unix-namestring new-name nil)))
750     (unless new-namestring
751       (error 'simple-file-error
752              :pathname new-name
753              :format-control "~S can't be created."
754              :format-arguments (list new-name)))
755     (multiple-value-bind (res error)
756         (sb!unix:unix-rename original-namestring new-namestring)
757       (unless res
758         (error 'simple-file-error
759                :pathname new-name
760                :format-control "failed to rename ~A to ~A: ~A"
761                :format-arguments (list original new-name
762                                        (sb!unix:get-unix-error-msg error))))
763       (when (streamp file)
764         (file-name file new-namestring))
765       (values new-name original (truename new-name)))))
766
767 (defun delete-file (file)
768   #!+sb-doc
769   "Delete the specified file."
770   (let ((namestring (unix-namestring file t)))
771     (when (streamp file)
772       (close file :abort t))
773     (unless namestring
774       (error 'simple-file-error
775              :pathname file
776              :format-control "~S doesn't exist."
777              :format-arguments (list file)))
778
779     (multiple-value-bind (res err) (sb!unix:unix-unlink namestring)
780       (unless res
781         (error 'simple-file-error
782                :pathname namestring
783                :format-control "could not delete ~A: ~A"
784                :format-arguments (list namestring
785                                        (sb!unix:get-unix-error-msg err))))))
786   t)
787 \f
788 ;;; Return Home:, which is set up for us at initialization time.
789 (defun user-homedir-pathname (&optional host)
790   #!+sb-doc
791   "Returns the home directory of the logged in user as a pathname.
792   This is obtained from the logical name \"home:\"."
793   (declare (ignore host))
794   ;; Note: CMU CL did #P"home:" here instead of using a call to
795   ;; PATHNAME. Delaying construction of the pathname until we're
796   ;; running in a target Lisp lets us avoid figuring out how to dump
797   ;; cross-compilation host Lisp PATHNAME objects into a target Lisp
798   ;; object file. It also might have a small positive effect on
799   ;; efficiency, in that we don't allocate a PATHNAME we don't need,
800   ;; but it it could also have a larger negative effect. Hopefully
801   ;; it'll be OK. -- WHN 19990714
802   (pathname "home:"))
803
804 (defun file-write-date (file)
805   #!+sb-doc
806   "Return file's creation date, or NIL if it doesn't exist.
807  An error of type file-error is signaled if file is a wild pathname"
808   (if (wild-pathname-p file)
809       ;; FIXME: This idiom appears many times in this file. Perhaps it
810       ;; should turn into (CANNOT-BE-WILD-PATHNAME FILE). (C-B-W-P
811       ;; should be a macro, not a function, so that the error message
812       ;; is reported as coming from e.g. FILE-WRITE-DATE instead of
813       ;; from CANNOT-BE-WILD-PATHNAME itself.)
814       (error 'simple-file-error
815              :pathname file
816              :format-control "bad place for a wild pathname")
817       (let ((name (unix-namestring file t)))
818         (when name
819           (multiple-value-bind
820               (res dev ino mode nlink uid gid rdev size atime mtime)
821               (sb!unix:unix-stat name)
822             (declare (ignore dev ino mode nlink uid gid rdev size atime))
823             (when res
824               (+ unix-to-universal-time mtime)))))))
825
826 (defun file-author (file)
827   #!+sb-doc
828   "Returns the file author as a string, or nil if the author cannot be
829  determined. Signals an error of type file-error if file doesn't exist,
830  or file is a wild pathname."
831   (if (wild-pathname-p file)
832       (error 'simple-file-error
833              :pathname file
834              "bad place for a wild pathname")
835       (let ((name (unix-namestring (pathname file) t)))
836         (unless name
837           (error 'simple-file-error
838                  :pathname file
839                  :format-control "~S doesn't exist."
840                  :format-arguments (list file)))
841         (multiple-value-bind (winp dev ino mode nlink uid)
842             (sb!unix:unix-stat name)
843           (declare (ignore dev ino mode nlink))
844           (if winp (lookup-login-name uid))))))
845 \f
846 ;;;; DIRECTORY
847
848 (/show0 "filesys.lisp 800")
849
850 (defun directory (pathname &key (all t) (check-for-subdirs t)
851                            (follow-links t))
852   #!+sb-doc
853   "Returns a list of pathnames, one for each file that matches the given
854    pathname. Supplying :ALL as nil causes this to ignore Unix dot files. This
855    never includes Unix dot and dot-dot in the result. If :FOLLOW-LINKS is NIL,
856    then symblolic links in the result are not expanded. This is not the
857    default because TRUENAME does follow links, and the result pathnames are
858    defined to be the TRUENAME of the pathname (the truename of a link may well
859    be in another directory.)"
860   (let ((results nil))
861     (enumerate-search-list
862         (pathname (merge-pathnames pathname
863                                    (make-pathname :name :wild
864                                                   :type :wild
865                                                   :version :wild)))
866       (enumerate-matches (name pathname)
867         (when (or all
868                   (let ((slash (position #\/ name :from-end t)))
869                     (or (null slash)
870                         (= (1+ slash) (length name))
871                         (char/= (schar name (1+ slash)) #\.))))
872           (push name results))))
873     (let ((*ignore-wildcards* t))
874       (mapcar #'(lambda (name)
875                   (let ((name (if (and check-for-subdirs
876                                        (eq (sb!unix:unix-file-kind name)
877                                            :directory))
878                                   (concatenate 'string name "/")
879                                   name)))
880                     (if follow-links (truename name) (pathname name))))
881               (sort (delete-duplicates results :test #'string=) #'string<)))))
882 \f
883 ;;;; translating Unix uid's
884 ;;;;
885 ;;;; FIXME: should probably move into unix.lisp
886
887 (defvar *uid-hash-table* (make-hash-table)
888   #!+sb-doc
889   "hash table for keeping track of uid's and login names")
890
891 (/show0 "filesys.lisp 844")
892
893 ;;; LOOKUP-LOGIN-NAME translates a user id into a login name. Previous
894 ;;; lookups are cached in a hash table since groveling the passwd(s)
895 ;;; files is somewhat expensive. The table may hold NIL for id's that
896 ;;; cannot be looked up since this keeps the files from having to be
897 ;;; searched in their entirety each time this id is translated.
898 (defun lookup-login-name (uid)
899   (multiple-value-bind (login-name foundp) (gethash uid *uid-hash-table*)
900     (if foundp
901         login-name
902         (setf (gethash uid *uid-hash-table*)
903               (get-group-or-user-name :user uid)))))
904
905 ;;; GET-GROUP-OR-USER-NAME first tries "/etc/passwd" ("/etc/group")
906 ;;; since it is a much smaller file, contains all the local id's, and
907 ;;; most uses probably involve id's on machines one would login into.
908 ;;; Then if necessary, we look in "/etc/passwds" ("/etc/groups") which
909 ;;; is really long and has to be fetched over the net.
910 ;;;
911 ;;; FIXME: Now that we no longer have lookup-group-name, we no longer need
912 ;;; the GROUP-OR-USER argument.
913 (defun get-group-or-user-name (group-or-user id)
914   #!+sb-doc
915   "Returns the simple-string user or group name of the user whose uid or gid
916    is id, or NIL if no such user or group exists. Group-or-user is either
917    :group or :user."
918   (let ((id-string (let ((*print-base* 10)) (prin1-to-string id))))
919     (declare (simple-string id-string))
920     (multiple-value-bind (file1 file2)
921         (ecase group-or-user
922           (:group (values "/etc/group" "/etc/groups"))
923           (:user (values "/etc/passwd" "/etc/passwd")))
924       (or (get-group-or-user-name-aux id-string file1)
925           (get-group-or-user-name-aux id-string file2)))))
926
927 ;;; FIXME: Isn't there now a POSIX routine to parse the passwd file?
928 ;;; getpwent? getpwuid?
929 (defun get-group-or-user-name-aux (id-string passwd-file)
930   (with-open-file (stream passwd-file)
931     (loop
932       (let ((entry (read-line stream nil)))
933         (unless entry (return nil))
934         (let ((name-end (position #\: (the simple-string entry)
935                                   :test #'char=)))
936           (when name-end
937             (let ((id-start (position #\: (the simple-string entry)
938                                       :start (1+ name-end) :test #'char=)))
939               (when id-start
940                 (incf id-start)
941                 (let ((id-end (position #\: (the simple-string entry)
942                                         :start id-start :test #'char=)))
943                   (when (and id-end
944                              (string= id-string entry
945                                       :start2 id-start :end2 id-end))
946                     (return (subseq entry 0 name-end))))))))))))
947 \f
948 (/show0 "filesys.lisp 899")
949
950 ;;; Predicate to order pathnames by. Goes by name.
951 (defun pathname-order (x y)
952   (let ((xn (%pathname-name x))
953         (yn (%pathname-name y)))
954     (if (and xn yn)
955         (let ((res (string-lessp xn yn)))
956           (cond ((not res) nil)
957                 ((= res (length (the simple-string xn))) t)
958                 ((= res (length (the simple-string yn))) nil)
959                 (t t)))
960         xn)))
961 \f
962 (defun default-directory ()
963   #!+sb-doc
964   "Returns the pathname for the default directory. This is the place where
965   a file will be written if no directory is specified. This may be changed
966   with setf."
967   (multiple-value-bind (gr dir-or-error) (sb!unix:unix-current-directory)
968     (if gr
969         (let ((*ignore-wildcards* t))
970           (pathname (concatenate 'simple-string dir-or-error "/")))
971         (error dir-or-error))))
972
973 (defun %set-default-directory (new-val)
974   (let ((namestring (unix-namestring new-val t)))
975     (unless namestring
976       (error "~S doesn't exist." new-val))
977     (multiple-value-bind (gr error) (sb!unix:unix-chdir namestring)
978       (if gr
979           (setf (search-list "default:") (default-directory))
980           (error (sb!unix:get-unix-error-msg error))))
981     new-val))
982
983 (/show0 "filesys.lisp 934")
984
985 (defun !filesys-cold-init ()
986   (/show0 "entering !FILESYS-COLD-INIT")
987   (setf *default-pathname-defaults*
988         (%make-pathname *unix-host* nil nil nil nil :newest))
989   (setf (search-list "default:") (default-directory))
990   (/show0 "leaving !FILESYS-COLD-INIT")
991   nil)
992 \f
993 (defun ensure-directories-exist (pathspec &key verbose (mode #o777))
994   #!+sb-doc
995   "Tests whether the directories containing the specified file
996   actually exist, and attempts to create them if they do not.
997   Portable programs should avoid using the :MODE keyword argument."
998   (let* ((pathname (pathname pathspec))
999          (pathname (if (typep pathname 'logical-pathname)
1000                        (translate-logical-pathname pathname)
1001                        pathname))
1002          (created-p nil))
1003     (when (wild-pathname-p pathname)
1004       (error 'simple-file-error
1005              :format-control "bad place for a wild pathname"
1006              :pathname pathspec))
1007     (enumerate-search-list (pathname pathname)
1008        (let ((dir (pathname-directory pathname)))
1009          (loop for i from 1 upto (length dir)
1010                do (let ((newpath (make-pathname
1011                                   :host (pathname-host pathname)
1012                                   :device (pathname-device pathname)
1013                                   :directory (subseq dir 0 i))))
1014                     (unless (probe-file newpath)
1015                       (let ((namestring (namestring newpath)))
1016                         (when verbose
1017                           (format *standard-output*
1018                                   "~&creating directory: ~A~%"
1019                                   namestring))
1020                         (sb!unix:unix-mkdir namestring mode)
1021                         (unless (probe-file namestring)
1022                           (error 'simple-file-error
1023                                  :pathname pathspec
1024                                  :format-control "can't create directory ~A"
1025                                  :format-arguments (list namestring)))
1026                         (setf created-p t)))))
1027          ;; Only the first path in a search-list is considered.
1028          (return (values pathname created-p))))))
1029
1030 (/show0 "filesys.lisp 1000")