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