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