0.6.9.18:
[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
170     ;; a valid 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 is true if absolute directories
203 ;;; location.
204 (defun split-at-slashes (namestr start end)
205   (declare (type simple-base-string namestr)
206            (type index start end))
207   (let ((absolute (and (/= start end)
208                        (char= (schar namestr start) #\/))))
209     (when absolute
210       (incf start))
211     ;; Next, split the remainder into slash-separated chunks.
212     (collect ((pieces))
213       (loop
214         (let ((slash (position #\/ namestr :start start :end end)))
215           (pieces (cons start (or slash end)))
216           (unless slash
217             (return))
218           (setf start (1+ slash))))
219       (values absolute (pieces)))))
220
221 (defun maybe-extract-search-list (namestr start end)
222   (declare (type simple-base-string namestr)
223            (type index start end))
224   (let ((quoted nil))
225     (do ((index start (1+ index)))
226         ((= index end)
227          (values nil start))
228       (if quoted
229           (setf quoted nil)
230           (case (schar namestr index)
231             (#\\
232              (setf quoted t))
233             (#\:
234              (return (values (remove-backslashes namestr start index)
235                              (1+ index)))))))))
236
237 (defun parse-unix-namestring (namestr start end)
238   (declare (type simple-base-string namestr)
239            (type index start end))
240   (multiple-value-bind (absolute pieces) (split-at-slashes namestr start end)
241     (let ((search-list (if absolute
242                            nil
243                            (let ((first (car pieces)))
244                              (multiple-value-bind (search-list new-start)
245                                  (maybe-extract-search-list namestr
246                                                             (car first)
247                                                             (cdr first))
248                                (when search-list
249                                  (setf absolute t)
250                                  (setf (car first) new-start))
251                                search-list)))))
252       (multiple-value-bind (name type version)
253           (let* ((tail (car (last pieces)))
254                  (tail-start (car tail))
255                  (tail-end (cdr tail)))
256             (unless (= tail-start tail-end)
257               (setf pieces (butlast pieces))
258               (extract-name-type-and-version namestr tail-start tail-end)))
259         ;; PVE: make sure there are no illegal characters in
260         ;; the name, illegal being (code-char 0) and #\/
261         #!+high-security
262         (when (and (stringp name)
263                    (find-if #'(lambda (x) (or (char= x (code-char 0))
264                                               (char= x #\/)))
265                             name))
266           (error 'parse-error))
267         
268         ;; Now we have everything we want. So return it.
269         (values nil ; no host for unix namestrings.
270                 nil ; no devices for unix namestrings.
271                 (collect ((dirs))
272                   (when search-list
273                     (dirs (intern-search-list search-list)))
274                   (dolist (piece pieces)
275                     (let ((piece-start (car piece))
276                           (piece-end (cdr piece)))
277                       (unless (= piece-start piece-end)
278                         (cond ((string= namestr ".." :start1 piece-start
279                                         :end1 piece-end)
280                                (dirs :up))
281                               ((string= namestr "**" :start1 piece-start
282                                         :end1 piece-end)
283                                (dirs :wild-inferiors))
284                               (t
285                                (dirs (maybe-make-pattern namestr
286                                                          piece-start
287                                                          piece-end)))))))
288                   (cond (absolute
289                          (cons :absolute (dirs)))
290                         ((dirs)
291                          (cons :relative (dirs)))
292                         (t
293                          nil)))
294                 name
295                 type
296                 version)))))
297
298 (/show0 "filesys.lisp 300")
299
300 (defun unparse-unix-host (pathname)
301   (declare (type pathname pathname)
302            (ignore pathname))
303   "Unix")
304
305 (defun unparse-unix-piece (thing)
306   (etypecase thing
307     ((member :wild) "*")
308     (simple-string
309      (let* ((srclen (length thing))
310             (dstlen srclen))
311        (dotimes (i srclen)
312          (case (schar thing i)
313            ((#\* #\? #\[)
314             (incf dstlen))))
315        (let ((result (make-string dstlen))
316              (dst 0))
317          (dotimes (src srclen)
318            (let ((char (schar thing src)))
319              (case char
320                ((#\* #\? #\[)
321                 (setf (schar result dst) #\\)
322                 (incf dst)))
323              (setf (schar result dst) char)
324              (incf dst)))
325          result)))
326     (pattern
327      (collect ((strings))
328        (dolist (piece (pattern-pieces thing))
329          (etypecase piece
330            (simple-string
331             (strings piece))
332            (symbol
333             (ecase piece
334               (:multi-char-wild
335                (strings "*"))
336               (:single-char-wild
337                (strings "?"))))
338            (cons
339             (case (car piece)
340               (:character-set
341                (strings "[")
342                (strings (cdr piece))
343                (strings "]"))
344               (t
345                (error "invalid pattern piece: ~S" piece))))))
346        (apply #'concatenate
347               'simple-string
348               (strings))))))
349
350 (defun unparse-unix-directory-list (directory)
351   (declare (type list directory))
352   (collect ((pieces))
353     (when directory
354       (ecase (pop directory)
355         (:absolute
356          (cond ((search-list-p (car directory))
357                 (pieces (search-list-name (pop directory)))
358                 (pieces ":"))
359                (t
360                 (pieces "/"))))
361         (:relative
362          ;; nothing special
363          ))
364       (dolist (dir directory)
365         (typecase dir
366           ((member :up)
367            (pieces "../"))
368           ((member :back)
369            (error ":BACK cannot be represented in namestrings."))
370           ((member :wild-inferiors)
371            (pieces "**/"))
372           ((or simple-string pattern)
373            (pieces (unparse-unix-piece dir))
374            (pieces "/"))
375           (t
376            (error "invalid directory component: ~S" dir)))))
377     (unless (null (pieces))
378       (apply #'concatenate 'simple-string (pieces)))))
379
380 (defun unparse-unix-directory (pathname)
381   (declare (type pathname pathname))
382   (unparse-unix-directory-list (%pathname-directory pathname)))
383
384 (defun unparse-unix-file (pathname)
385   (declare (type pathname pathname))
386   (collect ((strings))
387     (let* ((name (%pathname-name pathname))
388            (type (%pathname-type pathname))
389            (type-supplied (not (or (null type) (eq type :unspecific))))
390            (version (%pathname-version pathname))
391            (version-supplied (not (or (null version) (eq version :newest)))))
392       (when name
393         (strings (unparse-unix-piece name)))
394       (when type-supplied
395         (unless name
396           (error "cannot specify the type without a file: ~S" pathname))
397         (strings ".")
398         (strings (unparse-unix-piece type)))
399       (when version-supplied
400         (unless type-supplied
401           (error "cannot specify the version without a type: ~S" pathname))
402         (strings (if (eq version :wild)
403                      ".*"
404                      (format nil ".~D" version)))))
405     (unless (null (strings))
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
501 (defmacro enumerate-matches ((var pathname &optional result
502                                   &key (verify-existence t)
503                                   (follow-links t))
504                              &body body)
505   (let ((body-name (gensym)))
506     `(block nil
507        (flet ((,body-name (,var)
508                 ,@body))
509          (%enumerate-matches (pathname ,pathname)
510                              ,verify-existence
511                              ,follow-links
512                              #',body-name)
513          ,result))))
514
515 (/show0 "filesys.lisp 500")
516
517 (defun %enumerate-matches (pathname verify-existence follow-links function)
518   (/show0 "entering %ENUMERATE-MATCHES")
519   (when (pathname-type pathname)
520     (unless (pathname-name pathname)
521       (error "cannot supply a type without a name:~%  ~S" pathname)))
522   (when (and (integerp (pathname-version pathname))
523              (member (pathname-type pathname) '(nil :unspecific)))
524     (error "cannot supply a version without a type:~%  ~S" pathname))
525   (let ((directory (pathname-directory pathname)))
526     (/show0 "computed DIRECTORY")
527     (if directory
528         (ecase (car directory)
529           (:absolute
530            (/show0 "absolute directory")
531            (%enumerate-directories "/" (cdr directory) pathname
532                                    verify-existence follow-links
533                                    nil function))
534           (:relative
535            (/show0 "relative directory")
536            (%enumerate-directories "" (cdr directory) pathname
537                                    verify-existence follow-links
538                                    nil function)))
539         (%enumerate-files "" pathname verify-existence function))))
540
541 (defun %enumerate-directories (head tail pathname verify-existence
542                                follow-links nodes function)
543   (declare (simple-string head))
544   (macrolet ((unix-xstat (name)
545                `(if follow-links
546                     (sb!unix:unix-stat ,name)
547                     (sb!unix:unix-lstat ,name)))
548              (with-directory-node-noted ((head) &body body)
549                `(multiple-value-bind (res dev ino mode)
550                     (unix-xstat ,head)
551                   (when (and res (eql (logand mode sb!unix:s-ifmt)
552                                       sb!unix:s-ifdir))
553                     (let ((nodes (cons (cons dev ino) nodes)))
554                       ,@body))))
555              (do-directory-entries ((name directory) &body body)
556                `(let ((dir (sb!unix:open-dir ,directory)))
557              (when dir
558                (unwind-protect
559                    (loop
560                           (let ((,name (sb!unix:read-dir dir)))
561                             (cond ((null ,name)
562                               (return))
563                                   ((string= ,name "."))
564                                   ((string= ,name ".."))
565                                   (t
566                                    ,@body))))
567                       (sb!unix:close-dir dir))))))
568     (if tail
569         (let ((piece (car tail)))
570           (etypecase piece
571             (simple-string
572              (let ((head (concatenate 'string head piece)))
573                (with-directory-node-noted (head)
574                  (%enumerate-directories (concatenate 'string head "/")
575                                          (cdr tail) pathname
576                                          verify-existence follow-links
577                                          nodes function))))
578             ((member :wild-inferiors)
579              (%enumerate-directories head (rest tail) pathname
580                                      verify-existence follow-links
581                                      nodes function)
582              (do-directory-entries (name head)
583                (let ((subdir (concatenate 'string head name)))
584                  (multiple-value-bind (res dev ino mode)
585                      (unix-xstat subdir)
586                    (declare (type (or fixnum null) mode))
587                    (when (and res (eql (logand mode sb!unix:s-ifmt)
588                                        sb!unix:s-ifdir))
589                      (unless (dolist (dir nodes nil)
590                                (when (and (eql (car dir) dev)
591                                           (eql (cdr dir) ino))
592                                  (return t)))
593                        (let ((nodes (cons (cons dev ino) nodes))
594                              (subdir (concatenate 'string subdir "/")))
595                          (%enumerate-directories subdir tail pathname
596                                                  verify-existence follow-links
597                                                  nodes function))))))))
598             ((or pattern (member :wild))
599              (do-directory-entries (name head)
600                (when (or (eq piece :wild) (pattern-matches piece name))
601                  (let ((subdir (concatenate 'string head name)))
602                    (multiple-value-bind (res dev ino mode)
603                        (unix-xstat subdir)
604                      (declare (type (or fixnum null) mode))
605                      (when (and res
606                                 (eql (logand mode sb!unix:s-ifmt)
607                                      sb!unix:s-ifdir))
608                        (let ((nodes (cons (cons dev ino) nodes))
609                              (subdir (concatenate 'string subdir "/")))
610                          (%enumerate-directories subdir (rest tail) pathname
611                                                  verify-existence follow-links
612                                                  nodes function))))))))
613           ((member :up)
614              (let ((head (concatenate 'string head "..")))
615                (with-directory-node-noted (head)
616                  (%enumerate-directories (concatenate 'string head "/")
617                                          (rest tail) pathname
618                                          verify-existence follow-links
619                                          nodes function))))))
620         (%enumerate-files head pathname verify-existence function))))
621
622 (defun %enumerate-files (directory pathname verify-existence function)
623   (declare (simple-string directory))
624   (/show0 "entering %ENUMERATE-FILES")
625   (let ((name (%pathname-name pathname))
626         (type (%pathname-type pathname))
627         (version (%pathname-version pathname)))
628     (/show0 "computed NAME, TYPE, and VERSION")
629     (cond ((member name '(nil :unspecific))
630            (/show0 "UNSPECIFIC, more or less")
631            (when (or (not verify-existence)
632                      (sb!unix:unix-file-kind directory))
633              (funcall function directory)))
634           ((or (pattern-p name)
635                (pattern-p type)
636                (eq name :wild)
637                (eq type :wild))
638            (/show0 "WILD, more or less")
639            (let ((dir (sb!unix:open-dir directory)))
640              (when dir
641                (unwind-protect
642                    (loop
643                      (/show0 "at head of LOOP")
644                      (let ((file (sb!unix:read-dir dir)))
645                        (if file
646                            (unless (or (string= file ".")
647                                        (string= file ".."))
648                              (multiple-value-bind
649                                  (file-name file-type file-version)
650                                  (let ((*ignore-wildcards* t))
651                                    (extract-name-type-and-version
652                                     file 0 (length file)))
653                                (when (and (components-match file-name name)
654                                           (components-match file-type type)
655                                           (components-match file-version
656                                                             version))
657                                  (funcall function
658                                           (concatenate 'string
659                                                        directory
660                                                        file)))))
661                            (return))))
662                  (sb!unix:close-dir dir)))))
663           (t
664            (/show0 "default case")
665            (let ((file (concatenate 'string directory name)))
666              (/show0 "computed basic FILE=..")
667              #!+sb-show (%primitive print file)
668              (unless (or (null type) (eq type :unspecific))
669                (/show0 "tweaking FILE for more-or-less-:UNSPECIFIC case")
670                (setf file (concatenate 'string file "." type)))
671              (unless (member version '(nil :newest :wild))
672                (/show0 "tweaking FILE for more-or-less-:WILD case")
673                (setf file (concatenate 'string file "."
674                                        (quick-integer-to-string version))))
675              (/show0 "finished possibly tweaking FILE=..")
676              #!+sb-show (%primitive print file)
677              (when (or (not verify-existence)
678                        (sb!unix:unix-file-kind file t))
679                (/show0 "calling FUNCTION on FILE")
680                (funcall function file)))))))
681
682 (/show0 "filesys.lisp 603")
683
684 ;;; FIXME: Why do we need this?
685 (defun quick-integer-to-string (n)
686   (declare (type integer n))
687   (cond ((not (fixnump n))
688          (write-to-string n :base 10 :radix nil))
689         ((zerop n) "0")
690         ((eql n 1) "1")
691         ((minusp n)
692          (concatenate 'simple-string "-"
693                       (the simple-string (quick-integer-to-string (- n)))))
694         (t
695          (do* ((len (1+ (truncate (integer-length n) 3)))
696                (res (make-string len))
697                (i (1- len) (1- i))
698                (q n)
699                (r 0))
700               ((zerop q)
701                (incf i)
702                (replace res res :start2 i :end2 len)
703                (shrink-vector res (- len i)))
704            (declare (simple-string res)
705                     (fixnum len i r q))
706            (multiple-value-setq (q r) (truncate q 10))
707            (setf (schar res i) (schar "0123456789" r))))))
708 \f
709 ;;;; UNIX-NAMESTRING
710
711 (defun unix-namestring (pathname &optional (for-input t) executable-only)
712   #!+sb-doc
713   "Convert PATHNAME into a string that can be used with UNIX system calls.
714    Search-lists and wild-cards are expanded."
715   ;; toy@rtp.ericsson.se: Let unix-namestring also handle logical
716   ;; pathnames too.
717   ;; FIXME: What does this ^ mean? A bug? A remark on a change already made?
718   (let ((path (let ((lpn (pathname pathname)))
719                 (if (typep lpn 'logical-pathname)
720                     (namestring (translate-logical-pathname lpn))
721                     pathname))))
722     (enumerate-search-list
723       (pathname path)
724       (collect ((names))
725         (enumerate-matches (name pathname nil :verify-existence for-input)
726                            (when (or (not executable-only)
727                                      (and (eq (sb!unix:unix-file-kind name)
728                                               :file)
729                                           (sb!unix:unix-access name
730                                                                sb!unix:x_ok)))
731                              (names name)))
732         (let ((names (names)))
733           (when names
734             (when (cdr names)
735               (error 'simple-file-error
736                      :format-control "~S is ambiguous:~{~%  ~A~}"
737                      :format-arguments (list pathname names)))
738             (return (car names))))))))
739 \f
740 ;;;; TRUENAME and PROBE-FILE
741
742 ;;; Another silly file function trivially different from another function.
743 (defun truename (pathname)
744   #!+sb-doc
745   "Return the pathname for the actual file described by the pathname
746   An error of type file-error is signalled if no such file exists,
747   or the pathname is wild."
748   (if (wild-pathname-p pathname)
749       (error 'simple-file-error
750              :format-control "bad place for a wild pathname"
751              :pathname pathname)
752       (let ((result (probe-file pathname)))
753         (unless result
754           (error 'simple-file-error
755                  :pathname pathname
756                  :format-control "The file ~S does not exist."
757                  :format-arguments (list (namestring pathname))))
758         result)))
759
760 ;;; If PATHNAME exists, return its truename, otherwise NIL.
761 (defun probe-file (pathname)
762   #!+sb-doc
763   "Return a pathname which is the truename of the file if it exists, NIL
764   otherwise. An error of type FILE-ERROR is signaled if pathname is wild."
765   (if (wild-pathname-p pathname)
766       (error 'simple-file-error
767              :pathname pathname
768              :format-control "bad place for a wild pathname")
769       (let ((namestring (unix-namestring pathname t)))
770         (when (and namestring (sb!unix:unix-file-kind namestring))
771           (let ((truename (sb!unix:unix-resolve-links
772                            (sb!unix:unix-maybe-prepend-current-directory
773                             namestring))))
774             (when truename
775               (let ((*ignore-wildcards* t))
776                 (pathname (sb!unix:unix-simplify-pathname truename)))))))))
777 \f
778 ;;;; miscellaneous other operations
779
780 (/show0 "filesys.lisp 700")
781
782 (defun rename-file (file new-name)
783   #!+sb-doc
784   "Rename File to have the specified New-Name. If file is a stream open to a
785   file, then the associated file is renamed."
786   (let* ((original (truename file))
787          (original-namestring (unix-namestring original t))
788          (new-name (merge-pathnames new-name original))
789          (new-namestring (unix-namestring new-name nil)))
790     (unless new-namestring
791       (error 'simple-file-error
792              :pathname new-name
793              :format-control "~S can't be created."
794              :format-arguments (list new-name)))
795     (multiple-value-bind (res error)
796         (sb!unix:unix-rename original-namestring new-namestring)
797       (unless res
798         (error 'simple-file-error
799                :pathname new-name
800                :format-control "failed to rename ~A to ~A: ~A"
801                :format-arguments (list original new-name
802                                        (sb!unix:get-unix-error-msg error))))
803       (when (streamp file)
804         (file-name file new-namestring))
805       (values new-name original (truename new-name)))))
806
807 (defun delete-file (file)
808   #!+sb-doc
809   "Delete the specified file."
810   (let ((namestring (unix-namestring file t)))
811     (when (streamp file)
812       (close file :abort t))
813     (unless namestring
814       (error 'simple-file-error
815              :pathname file
816              :format-control "~S doesn't exist."
817              :format-arguments (list file)))
818
819     (multiple-value-bind (res err) (sb!unix:unix-unlink namestring)
820       (unless res
821         (error 'simple-file-error
822                :pathname namestring
823                :format-control "could not delete ~A: ~A"
824                :format-arguments (list namestring
825                                        (sb!unix:get-unix-error-msg err))))))
826   t)
827 \f
828 ;;; Return Home:, which is set up for us at initialization time.
829 (defun user-homedir-pathname (&optional host)
830   #!+sb-doc
831   "Returns the home directory of the logged in user as a pathname.
832   This is obtained from the logical name \"home:\"."
833   (declare (ignore host))
834   ;; Note: CMU CL did #P"home:" here instead of using a call to
835   ;; PATHNAME. Delaying construction of the pathname until we're
836   ;; running in a target Lisp lets us avoid figuring out how to dump
837   ;; cross-compilation host Lisp PATHNAME objects into a target Lisp
838   ;; object file. It also might have a small positive effect on
839   ;; efficiency, in that we don't allocate a PATHNAME we don't need,
840   ;; but it it could also have a larger negative effect. Hopefully
841   ;; it'll be OK. -- WHN 19990714
842   (pathname "home:"))
843
844 (defun file-write-date (file)
845   #!+sb-doc
846   "Return file's creation date, or NIL if it doesn't exist.
847  An error of type file-error is signaled if file is a wild pathname"
848   (if (wild-pathname-p file)
849       ;; FIXME: This idiom appears many times in this file. Perhaps it
850       ;; should turn into (CANNOT-BE-WILD-PATHNAME FILE). (C-B-W-P
851       ;; should be a macro, not a function, so that the error message
852       ;; is reported as coming from e.g. FILE-WRITE-DATE instead of
853       ;; from CANNOT-BE-WILD-PATHNAME itself.)
854       (error 'simple-file-error
855              :pathname file
856              :format-control "bad place for a wild pathname")
857       (let ((name (unix-namestring file t)))
858         (when name
859           (multiple-value-bind
860               (res dev ino mode nlink uid gid rdev size atime mtime)
861               (sb!unix:unix-stat name)
862             (declare (ignore dev ino mode nlink uid gid rdev size atime))
863             (when res
864               (+ unix-to-universal-time mtime)))))))
865
866 (defun file-author (file)
867   #!+sb-doc
868   "Returns the file author as a string, or nil if the author cannot be
869  determined. Signals an error of type file-error if file doesn't exist,
870  or file is a wild pathname."
871   (if (wild-pathname-p file)
872       (error 'simple-file-error
873              :pathname file
874              "bad place for a wild pathname")
875       (let ((name (unix-namestring (pathname file) t)))
876         (unless name
877           (error 'simple-file-error
878                  :pathname file
879                  :format-control "~S doesn't exist."
880                  :format-arguments (list file)))
881         (multiple-value-bind (winp dev ino mode nlink uid)
882             (sb!unix:unix-stat name)
883           (declare (ignore dev ino mode nlink))
884           (if winp (lookup-login-name uid))))))
885 \f
886 ;;;; DIRECTORY
887
888 (/show0 "filesys.lisp 800")
889
890 (defun directory (pathname &key (all t) (check-for-subdirs t)
891                            (follow-links t))
892   #!+sb-doc
893   "Returns a list of pathnames, one for each file that matches the given
894    pathname. Supplying :ALL as nil causes this to ignore Unix dot files. This
895    never includes Unix dot and dot-dot in the result. If :FOLLOW-LINKS is NIL,
896    then symblolic links in the result are not expanded. This is not the
897    default because TRUENAME does follow links, and the result pathnames are
898    defined to be the TRUENAME of the pathname (the truename of a link may well
899    be in another directory.)"
900   (let ((results nil))
901     (enumerate-search-list
902         (pathname (merge-pathnames pathname
903                                    (make-pathname :name :wild
904                                                   :type :wild
905                                                   :version :wild)))
906       (enumerate-matches (name pathname)
907         (when (or all
908                   (let ((slash (position #\/ name :from-end t)))
909                     (or (null slash)
910                         (= (1+ slash) (length name))
911                         (char/= (schar name (1+ slash)) #\.))))
912           (push name results))))
913     (let ((*ignore-wildcards* t))
914       (mapcar #'(lambda (name)
915                   (let ((name (if (and check-for-subdirs
916                                        (eq (sb!unix:unix-file-kind name)
917                                            :directory))
918                                   (concatenate 'string name "/")
919                                   name)))
920                     (if follow-links (truename name) (pathname name))))
921               (sort (delete-duplicates results :test #'string=) #'string<)))))
922 \f
923 ;;;; translating Unix uid's
924 ;;;;
925 ;;;; FIXME: should probably move into unix.lisp
926
927 (defvar *uid-hash-table* (make-hash-table)
928   #!+sb-doc
929   "hash table for keeping track of uid's and login names")
930
931 (/show0 "filesys.lisp 844")
932
933 ;;; LOOKUP-LOGIN-NAME translates a user id into a login name. Previous
934 ;;; lookups are cached in a hash table since groveling the passwd(s)
935 ;;; files is somewhat expensive. The table may hold NIL for id's that
936 ;;; cannot be looked up since this keeps the files from having to be
937 ;;; searched in their entirety each time this id is translated.
938 (defun lookup-login-name (uid)
939   (multiple-value-bind (login-name foundp) (gethash uid *uid-hash-table*)
940     (if foundp
941         login-name
942         (setf (gethash uid *uid-hash-table*)
943               (get-group-or-user-name :user uid)))))
944
945 ;;; GET-GROUP-OR-USER-NAME first tries "/etc/passwd" ("/etc/group")
946 ;;; since it is a much smaller file, contains all the local id's, and
947 ;;; most uses probably involve id's on machines one would login into.
948 ;;; Then if necessary, we look in "/etc/passwds" ("/etc/groups") which
949 ;;; is really long and has to be fetched over the net.
950 ;;;
951 ;;; FIXME: Now that we no longer have lookup-group-name, we no longer need
952 ;;; the GROUP-OR-USER argument.
953 (defun get-group-or-user-name (group-or-user id)
954   #!+sb-doc
955   "Returns the simple-string user or group name of the user whose uid or gid
956    is id, or NIL if no such user or group exists. Group-or-user is either
957    :group or :user."
958   (let ((id-string (let ((*print-base* 10)) (prin1-to-string id))))
959     (declare (simple-string id-string))
960     (multiple-value-bind (file1 file2)
961         (ecase group-or-user
962           (:group (values "/etc/group" "/etc/groups"))
963           (:user (values "/etc/passwd" "/etc/passwd")))
964       (or (get-group-or-user-name-aux id-string file1)
965           (get-group-or-user-name-aux id-string file2)))))
966
967 ;;; FIXME: Isn't there now a POSIX routine to parse the passwd file?
968 ;;; getpwent? getpwuid?
969 (defun get-group-or-user-name-aux (id-string passwd-file)
970   (with-open-file (stream passwd-file)
971     (loop
972       (let ((entry (read-line stream nil)))
973         (unless entry (return nil))
974         (let ((name-end (position #\: (the simple-string entry)
975                                   :test #'char=)))
976           (when name-end
977             (let ((id-start (position #\: (the simple-string entry)
978                                       :start (1+ name-end) :test #'char=)))
979               (when id-start
980                 (incf id-start)
981                 (let ((id-end (position #\: (the simple-string entry)
982                                         :start id-start :test #'char=)))
983                   (when (and id-end
984                              (string= id-string entry
985                                       :start2 id-start :end2 id-end))
986                     (return (subseq entry 0 name-end))))))))))))
987 \f
988 (/show0 "filesys.lisp 899")
989
990 ;;; Predicate to order pathnames by. Goes by name.
991 (defun pathname-order (x y)
992   (let ((xn (%pathname-name x))
993         (yn (%pathname-name y)))
994     (if (and xn yn)
995         (let ((res (string-lessp xn yn)))
996           (cond ((not res) nil)
997                 ((= res (length (the simple-string xn))) t)
998                 ((= res (length (the simple-string yn))) nil)
999                 (t t)))
1000         xn)))
1001 \f
1002 (defun default-directory ()
1003   #!+sb-doc
1004   "Returns the pathname for the default directory. This is the place where
1005   a file will be written if no directory is specified. This may be changed
1006   with setf."
1007   (multiple-value-bind (gr dir-or-error) (sb!unix:unix-current-directory)
1008     (if gr
1009         (let ((*ignore-wildcards* t))
1010           (pathname (concatenate 'simple-string dir-or-error "/")))
1011         (error dir-or-error))))
1012
1013 (defun %set-default-directory (new-val)
1014   (let ((namestring (unix-namestring new-val t)))
1015     (unless namestring
1016       (error "~S doesn't exist." new-val))
1017     (multiple-value-bind (gr error) (sb!unix:unix-chdir namestring)
1018       (if gr
1019           (setf (search-list "default:") (default-directory))
1020           (error (sb!unix:get-unix-error-msg error))))
1021     new-val))
1022
1023 (/show0 "filesys.lisp 934")
1024
1025 (/show0 "entering what used to be !FILESYS-COLD-INIT")
1026 (defvar *default-pathname-defaults*
1027   (%make-pathname *unix-host* nil nil nil nil :newest))
1028 (setf (search-list "default:") (default-directory))
1029 (/show0 "leaving what used to be !FILESYS-COLD-INIT")
1030 \f
1031 (defun ensure-directories-exist (pathspec &key verbose (mode #o777))
1032   #!+sb-doc
1033   "Tests whether the directories containing the specified file
1034   actually exist, and attempts to create them if they do not.
1035   Portable programs should avoid using the :MODE keyword argument."
1036   (let* ((pathname (pathname pathspec))
1037          (pathname (if (typep pathname 'logical-pathname)
1038                        (translate-logical-pathname pathname)
1039                        pathname))
1040          (created-p nil))
1041     (when (wild-pathname-p pathname)
1042       (error 'simple-file-error
1043              :format-control "bad place for a wild pathname"
1044              :pathname pathspec))
1045     (enumerate-search-list (pathname pathname)
1046        (let ((dir (pathname-directory pathname)))
1047          (loop for i from 1 upto (length dir)
1048                do (let ((newpath (make-pathname
1049                                   :host (pathname-host pathname)
1050                                   :device (pathname-device pathname)
1051                                   :directory (subseq dir 0 i))))
1052                     (unless (probe-file newpath)
1053                       (let ((namestring (namestring newpath)))
1054                         (when verbose
1055                           (format *standard-output*
1056                                   "~&creating directory: ~A~%"
1057                                   namestring))
1058                         (sb!unix:unix-mkdir namestring mode)
1059                         (unless (probe-file namestring)
1060                           (error 'simple-file-error
1061                                  :pathname pathspec
1062                                  :format-control "can't create directory ~A"
1063                                  :format-arguments (list namestring)))
1064                         (setf created-p t)))))
1065          ;; Only the first path in a search-list is considered.
1066          (return (values pathname created-p))))))
1067
1068 (/show0 "filesys.lisp 1000")