0.6.11.13:
[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     (apply #'concatenate 'simple-string (pieces))))
378
379 (defun unparse-unix-directory (pathname)
380   (declare (type pathname pathname))
381   (unparse-unix-directory-list (%pathname-directory pathname)))
382
383 (defun unparse-unix-file (pathname)
384   (declare (type pathname pathname))
385   (collect ((strings))
386     (let* ((name (%pathname-name pathname))
387            (type (%pathname-type pathname))
388            (type-supplied (not (or (null type) (eq type :unspecific))))
389            (version (%pathname-version pathname))
390            (version-supplied (not (or (null version) (eq version :newest)))))
391       (when name
392         (strings (unparse-unix-piece name)))
393       (when type-supplied
394         (unless name
395           (error "cannot specify the type without a file: ~S" pathname))
396         (strings ".")
397         (strings (unparse-unix-piece type)))
398       (when version-supplied
399         (unless type-supplied
400           (error "cannot specify the version without a type: ~S" pathname))
401         (strings (if (eq version :wild)
402                      ".*"
403                      (format nil ".~D" version)))))
404     (apply #'concatenate 'simple-string (strings))))
405
406 (/show0 "filesys.lisp 406")
407
408 (defun unparse-unix-namestring (pathname)
409   (declare (type pathname pathname))
410   (concatenate 'simple-string
411                (unparse-unix-directory pathname)
412                (unparse-unix-file pathname)))
413
414 (defun unparse-unix-enough (pathname defaults)
415   (declare (type pathname pathname defaults))
416   (flet ((lose ()
417            (error "~S cannot be represented relative to ~S."
418                   pathname defaults)))
419     (collect ((strings))
420       (let* ((pathname-directory (%pathname-directory pathname))
421              (defaults-directory (%pathname-directory defaults))
422              (prefix-len (length defaults-directory))
423              (result-dir
424               (cond ((and (> prefix-len 1)
425                           (>= (length pathname-directory) prefix-len)
426                           (compare-component (subseq pathname-directory
427                                                      0 prefix-len)
428                                              defaults-directory))
429                      ;; Pathname starts with a prefix of default. So
430                      ;; just use a relative directory from then on out.
431                      (cons :relative (nthcdr prefix-len pathname-directory)))
432                     ((eq (car pathname-directory) :absolute)
433                      ;; We are an absolute pathname, so we can just use it.
434                      pathname-directory)
435                     (t
436                      ;; We are a relative directory. So we lose.
437                      (lose)))))
438         (strings (unparse-unix-directory-list result-dir)))
439       (let* ((pathname-version (%pathname-version pathname))
440              (version-needed (and pathname-version
441                                   (not (eq pathname-version :newest))))
442              (pathname-type (%pathname-type pathname))
443              (type-needed (or version-needed
444                               (and pathname-type
445                                    (not (eq pathname-type :unspecific)))))
446              (pathname-name (%pathname-name pathname))
447              (name-needed (or type-needed
448                               (and pathname-name
449                                    (not (compare-component pathname-name
450                                                            (%pathname-name
451                                                             defaults)))))))
452         (when name-needed
453           (unless pathname-name (lose))
454           (strings (unparse-unix-piece pathname-name)))
455         (when type-needed
456           (when (or (null pathname-type) (eq pathname-type :unspecific))
457             (lose))
458           (strings ".")
459           (strings (unparse-unix-piece pathname-type)))
460         (when version-needed
461           (typecase pathname-version
462             ((member :wild)
463              (strings ".*"))
464             (integer
465              (strings (format nil ".~D" pathname-version)))
466             (t
467              (lose)))))
468       (apply #'concatenate 'simple-string (strings)))))
469
470 (/show0 "filesys.lisp 471")
471
472 (def!struct (unix-host
473              (:make-load-form-fun make-unix-host-load-form)
474              (:include host
475                        (parse #'parse-unix-namestring)
476                        (unparse #'unparse-unix-namestring)
477                        (unparse-host #'unparse-unix-host)
478                        (unparse-directory #'unparse-unix-directory)
479                        (unparse-file #'unparse-unix-file)
480                        (unparse-enough #'unparse-unix-enough)
481                        (customary-case :lower))))
482
483 (/show0 "filesys.lisp 486")
484
485 (defvar *unix-host* (make-unix-host))
486
487 (/show0 "filesys.lisp 488")
488
489 (defun make-unix-host-load-form (host)
490   (declare (ignore host))
491   '*unix-host*)
492 \f
493 ;;;; wildcard matching stuff
494
495 (/show0 "filesys.lisp 498")
496
497 ;;; FIXME: could maybe be EVAL-WHEN (COMPILE EVAL)
498
499 (defmacro enumerate-matches ((var pathname &optional result
500                                   &key (verify-existence t)
501                                   (follow-links t))
502                              &body body)
503   (let ((body-name (gensym)))
504     `(block nil
505        (flet ((,body-name (,var)
506                 ,@body))
507          (%enumerate-matches (pathname ,pathname)
508                              ,verify-existence
509                              ,follow-links
510                              #',body-name)
511          ,result))))
512
513 (/show0 "filesys.lisp 500")
514
515 (defun %enumerate-matches (pathname verify-existence follow-links function)
516   (/show0 "entering %ENUMERATE-MATCHES")
517   (when (pathname-type pathname)
518     (unless (pathname-name pathname)
519       (error "cannot supply a type without a name:~%  ~S" pathname)))
520   (when (and (integerp (pathname-version pathname))
521              (member (pathname-type pathname) '(nil :unspecific)))
522     (error "cannot supply a version without a type:~%  ~S" pathname))
523   (let ((directory (pathname-directory pathname)))
524     (/show0 "computed DIRECTORY")
525     (if directory
526         (ecase (car directory)
527           (:absolute
528            (/show0 "absolute directory")
529            (%enumerate-directories "/" (cdr directory) pathname
530                                    verify-existence follow-links
531                                    nil function))
532           (:relative
533            (/show0 "relative directory")
534            (%enumerate-directories "" (cdr directory) pathname
535                                    verify-existence follow-links
536                                    nil function)))
537         (%enumerate-files "" pathname verify-existence function))))
538
539 (defun %enumerate-directories (head tail pathname verify-existence
540                                follow-links nodes function)
541   (declare (simple-string head))
542   (macrolet ((unix-xstat (name)
543                `(if follow-links
544                     (sb!unix:unix-stat ,name)
545                     (sb!unix:unix-lstat ,name)))
546              (with-directory-node-noted ((head) &body body)
547                `(multiple-value-bind (res dev ino mode)
548                     (unix-xstat ,head)
549                   (when (and res (eql (logand mode sb!unix:s-ifmt)
550                                       sb!unix:s-ifdir))
551                     (let ((nodes (cons (cons dev ino) nodes)))
552                       ,@body))))
553              (do-directory-entries ((name directory) &body body)
554                `(let ((dir (sb!unix:open-dir ,directory)))
555              (when dir
556                (unwind-protect
557                    (loop
558                           (let ((,name (sb!unix:read-dir dir)))
559                             (cond ((null ,name)
560                               (return))
561                                   ((string= ,name "."))
562                                   ((string= ,name ".."))
563                                   (t
564                                    ,@body))))
565                       (sb!unix:close-dir dir))))))
566     (if tail
567         (let ((piece (car tail)))
568           (etypecase piece
569             (simple-string
570              (let ((head (concatenate 'string head piece)))
571                (with-directory-node-noted (head)
572                  (%enumerate-directories (concatenate 'string head "/")
573                                          (cdr tail) pathname
574                                          verify-existence follow-links
575                                          nodes function))))
576             ((member :wild-inferiors)
577              (%enumerate-directories head (rest tail) pathname
578                                      verify-existence follow-links
579                                      nodes function)
580              (do-directory-entries (name head)
581                (let ((subdir (concatenate 'string head name)))
582                  (multiple-value-bind (res dev ino mode)
583                      (unix-xstat subdir)
584                    (declare (type (or fixnum null) mode))
585                    (when (and res (eql (logand mode sb!unix:s-ifmt)
586                                        sb!unix:s-ifdir))
587                      (unless (dolist (dir nodes nil)
588                                (when (and (eql (car dir) dev)
589                                           (eql (cdr dir) ino))
590                                  (return t)))
591                        (let ((nodes (cons (cons dev ino) nodes))
592                              (subdir (concatenate 'string subdir "/")))
593                          (%enumerate-directories subdir tail pathname
594                                                  verify-existence follow-links
595                                                  nodes function))))))))
596             ((or pattern (member :wild))
597              (do-directory-entries (name head)
598                (when (or (eq piece :wild) (pattern-matches piece name))
599                  (let ((subdir (concatenate 'string head name)))
600                    (multiple-value-bind (res dev ino mode)
601                        (unix-xstat subdir)
602                      (declare (type (or fixnum null) mode))
603                      (when (and res
604                                 (eql (logand mode sb!unix:s-ifmt)
605                                      sb!unix:s-ifdir))
606                        (let ((nodes (cons (cons dev ino) nodes))
607                              (subdir (concatenate 'string subdir "/")))
608                          (%enumerate-directories subdir (rest tail) pathname
609                                                  verify-existence follow-links
610                                                  nodes function))))))))
611           ((member :up)
612              (let ((head (concatenate 'string head "..")))
613                (with-directory-node-noted (head)
614                  (%enumerate-directories (concatenate 'string head "/")
615                                          (rest tail) pathname
616                                          verify-existence follow-links
617                                          nodes function))))))
618         (%enumerate-files head pathname verify-existence function))))
619
620 (defun %enumerate-files (directory pathname verify-existence function)
621   (declare (simple-string directory))
622   (/show0 "entering %ENUMERATE-FILES")
623   (let ((name (%pathname-name pathname))
624         (type (%pathname-type pathname))
625         (version (%pathname-version pathname)))
626     (/show0 "computed NAME, TYPE, and VERSION")
627     (cond ((member name '(nil :unspecific))
628            (/show0 "UNSPECIFIC, more or less")
629            (when (or (not verify-existence)
630                      (sb!unix:unix-file-kind directory))
631              (funcall function directory)))
632           ((or (pattern-p name)
633                (pattern-p type)
634                (eq name :wild)
635                (eq type :wild))
636            (/show0 "WILD, more or less")
637            (let ((dir (sb!unix:open-dir directory)))
638              (when dir
639                (unwind-protect
640                    (loop
641                      (/show0 "at head of LOOP")
642                      (let ((file (sb!unix:read-dir dir)))
643                        (if file
644                            (unless (or (string= file ".")
645                                        (string= file ".."))
646                              (multiple-value-bind
647                                  (file-name file-type file-version)
648                                  (let ((*ignore-wildcards* t))
649                                    (extract-name-type-and-version
650                                     file 0 (length file)))
651                                (when (and (components-match file-name name)
652                                           (components-match file-type type)
653                                           (components-match file-version
654                                                             version))
655                                  (funcall function
656                                           (concatenate 'string
657                                                        directory
658                                                        file)))))
659                            (return))))
660                  (sb!unix:close-dir dir)))))
661           (t
662            (/show0 "default case")
663            (let ((file (concatenate 'string directory name)))
664              (/show0 "computed basic FILE=..")
665              (/primitive-print file)
666              (unless (or (null type) (eq type :unspecific))
667                (/show0 "tweaking FILE for more-or-less-:UNSPECIFIC case")
668                (setf file (concatenate 'string file "." type)))
669              (unless (member version '(nil :newest :wild))
670                (/show0 "tweaking FILE for more-or-less-:WILD case")
671                (setf file (concatenate 'string file "."
672                                        (quick-integer-to-string version))))
673              (/show0 "finished possibly tweaking FILE=..")
674              (/primitive-print file)
675              (when (or (not verify-existence)
676                        (sb!unix:unix-file-kind file t))
677                (/show0 "calling FUNCTION on FILE")
678                (funcall function file)))))))
679
680 (/show0 "filesys.lisp 603")
681
682 ;;; FIXME: Why do we need this?
683 (defun quick-integer-to-string (n)
684   (declare (type integer n))
685   (cond ((not (fixnump n))
686          (write-to-string n :base 10 :radix nil))
687         ((zerop n) "0")
688         ((eql n 1) "1")
689         ((minusp n)
690          (concatenate 'simple-string "-"
691                       (the simple-string (quick-integer-to-string (- n)))))
692         (t
693          (do* ((len (1+ (truncate (integer-length n) 3)))
694                (res (make-string len))
695                (i (1- len) (1- i))
696                (q n)
697                (r 0))
698               ((zerop q)
699                (incf i)
700                (replace res res :start2 i :end2 len)
701                (shrink-vector res (- len i)))
702            (declare (simple-string res)
703                     (fixnum len i r q))
704            (multiple-value-setq (q r) (truncate q 10))
705            (setf (schar res i) (schar "0123456789" r))))))
706 \f
707 ;;;; UNIX-NAMESTRING
708
709 (defun unix-namestring (pathname &optional (for-input t) executable-only)
710   #!+sb-doc
711   "Convert PATHNAME into a string that can be used with UNIX system calls.
712    Search-lists and wild-cards are expanded."
713   ;; toy@rtp.ericsson.se: Let unix-namestring also handle logical
714   ;; pathnames too.
715   ;; FIXME: What does this ^ mean? A bug? A remark on a change already made?
716   (let ((path (let ((lpn (pathname pathname)))
717                 (if (typep lpn 'logical-pathname)
718                     (namestring (translate-logical-pathname lpn))
719                     pathname))))
720     (enumerate-search-list
721       (pathname path)
722       (collect ((names))
723         (enumerate-matches (name pathname nil :verify-existence for-input)
724                            (when (or (not executable-only)
725                                      (and (eq (sb!unix:unix-file-kind name)
726                                               :file)
727                                           (sb!unix:unix-access name
728                                                                sb!unix:x_ok)))
729                              (names name)))
730         (let ((names (names)))
731           (when names
732             (when (cdr names)
733               (error 'simple-file-error
734                      :format-control "~S is ambiguous:~{~%  ~A~}"
735                      :format-arguments (list pathname names)))
736             (return (car names))))))))
737 \f
738 ;;;; TRUENAME and PROBE-FILE
739
740 ;;; Another silly file function trivially different from another function.
741 (defun truename (pathname)
742   #!+sb-doc
743   "Return the pathname for the actual file described by the pathname
744   An error of type file-error is signalled if no such file exists,
745   or the pathname is wild."
746   (if (wild-pathname-p pathname)
747       (error 'simple-file-error
748              :format-control "bad place for a wild pathname"
749              :pathname pathname)
750       (let ((result (probe-file pathname)))
751         (unless result
752           (error 'simple-file-error
753                  :pathname pathname
754                  :format-control "The file ~S does not exist."
755                  :format-arguments (list (namestring pathname))))
756         result)))
757
758 ;;; If PATHNAME exists, return its truename, otherwise NIL.
759 (defun probe-file (pathname)
760   #!+sb-doc
761   "Return a pathname which is the truename of the file if it exists, NIL
762   otherwise. An error of type FILE-ERROR is signaled if pathname is wild."
763   (if (wild-pathname-p pathname)
764       (error 'simple-file-error
765              :pathname pathname
766              :format-control "bad place for a wild pathname")
767       (let ((namestring (unix-namestring pathname t)))
768         (when (and namestring (sb!unix:unix-file-kind namestring))
769           (let ((truename (sb!unix:unix-resolve-links
770                            (sb!unix:unix-maybe-prepend-current-directory
771                             namestring))))
772             (when truename
773               (let ((*ignore-wildcards* t))
774                 (pathname (sb!unix:unix-simplify-pathname truename)))))))))
775 \f
776 ;;;; miscellaneous other operations
777
778 (/show0 "filesys.lisp 700")
779
780 (defun rename-file (file new-name)
781   #!+sb-doc
782   "Rename File to have the specified New-Name. If file is a stream open to a
783   file, then the associated file is renamed."
784   (let* ((original (truename file))
785          (original-namestring (unix-namestring original t))
786          (new-name (merge-pathnames new-name original))
787          (new-namestring (unix-namestring new-name nil)))
788     (unless new-namestring
789       (error 'simple-file-error
790              :pathname new-name
791              :format-control "~S can't be created."
792              :format-arguments (list new-name)))
793     (multiple-value-bind (res error)
794         (sb!unix:unix-rename original-namestring new-namestring)
795       (unless res
796         (error 'simple-file-error
797                :pathname new-name
798                :format-control "failed to rename ~A to ~A: ~A"
799                :format-arguments (list original new-name
800                                        (sb!unix:get-unix-error-msg error))))
801       (when (streamp file)
802         (file-name file new-namestring))
803       (values new-name original (truename new-name)))))
804
805 (defun delete-file (file)
806   #!+sb-doc
807   "Delete the specified file."
808   (let ((namestring (unix-namestring file t)))
809     (when (streamp file)
810       (close file :abort t))
811     (unless namestring
812       (error 'simple-file-error
813              :pathname file
814              :format-control "~S doesn't exist."
815              :format-arguments (list file)))
816
817     (multiple-value-bind (res err) (sb!unix:unix-unlink namestring)
818       (unless res
819         (error 'simple-file-error
820                :pathname namestring
821                :format-control "could not delete ~A: ~A"
822                :format-arguments (list namestring
823                                        (sb!unix:get-unix-error-msg err))))))
824   t)
825 \f
826 ;;; Return Home:, which is set up for us at initialization time.
827 (defun user-homedir-pathname (&optional host)
828   #!+sb-doc
829   "Returns the home directory of the logged in user as a pathname.
830   This is obtained from the logical name \"home:\"."
831   (declare (ignore host))
832   ;; Note: CMU CL did #P"home:" here instead of using a call to
833   ;; PATHNAME. Delaying construction of the pathname until we're
834   ;; running in a target Lisp lets us avoid figuring out how to dump
835   ;; cross-compilation host Lisp PATHNAME objects into a target Lisp
836   ;; object file. It also might have a small positive effect on
837   ;; efficiency, in that we don't allocate a PATHNAME we don't need,
838   ;; but it it could also have a larger negative effect. Hopefully
839   ;; it'll be OK. -- WHN 19990714
840   (pathname "home:"))
841
842 (defun file-write-date (file)
843   #!+sb-doc
844   "Return file's creation date, or NIL if it doesn't exist.
845  An error of type file-error is signaled if file is a wild pathname"
846   (if (wild-pathname-p file)
847       ;; FIXME: This idiom appears many times in this file. Perhaps it
848       ;; should turn into (CANNOT-BE-WILD-PATHNAME FILE). (C-B-W-P
849       ;; should be a macro, not a function, so that the error message
850       ;; is reported as coming from e.g. FILE-WRITE-DATE instead of
851       ;; from CANNOT-BE-WILD-PATHNAME itself.)
852       (error 'simple-file-error
853              :pathname file
854              :format-control "bad place for a wild pathname")
855       (let ((name (unix-namestring file t)))
856         (when name
857           (multiple-value-bind
858               (res dev ino mode nlink uid gid rdev size atime mtime)
859               (sb!unix:unix-stat name)
860             (declare (ignore dev ino mode nlink uid gid rdev size atime))
861             (when res
862               (+ unix-to-universal-time mtime)))))))
863
864 (defun file-author (file)
865   #!+sb-doc
866   "Returns the file author as a string, or nil if the author cannot be
867  determined. Signals an error of type file-error if file doesn't exist,
868  or file is a wild pathname."
869   (if (wild-pathname-p file)
870       (error 'simple-file-error
871              :pathname file
872              "bad place for a wild pathname")
873       (let ((name (unix-namestring (pathname file) t)))
874         (unless name
875           (error 'simple-file-error
876                  :pathname file
877                  :format-control "~S doesn't exist."
878                  :format-arguments (list file)))
879         (multiple-value-bind (winp dev ino mode nlink uid)
880             (sb!unix:unix-stat name)
881           (declare (ignore dev ino mode nlink))
882           (if winp (lookup-login-name uid))))))
883 \f
884 ;;;; DIRECTORY
885
886 (/show0 "filesys.lisp 800")
887
888 (defun directory (pathname &key (all t) (check-for-subdirs t)
889                            (follow-links t))
890   #!+sb-doc
891   "Returns a list of pathnames, one for each file that matches the given
892    pathname. Supplying :ALL as NIL causes this to ignore Unix dot files. This
893    never includes Unix dot and dot-dot in the result. If :FOLLOW-LINKS is NIL,
894    then symbolic links in the result are not expanded. This is not the
895    default because TRUENAME does follow links, and the result pathnames are
896    defined to be the TRUENAME of the pathname (the truename of a link may well
897    be in another directory.)"
898   (let ((results nil))
899     (enumerate-search-list
900         (pathname (merge-pathnames pathname
901                                    (make-pathname :name :wild
902                                                   :type :wild
903                                                   :version :wild)))
904       (enumerate-matches (name pathname)
905         (when (or all
906                   (let ((slash (position #\/ name :from-end t)))
907                     (or (null slash)
908                         (= (1+ slash) (length name))
909                         (char/= (schar name (1+ slash)) #\.))))
910           (push name results))))
911     (let ((*ignore-wildcards* t))
912       (mapcar (lambda (name)
913                 (let ((name (if (and check-for-subdirs
914                                      (eq (sb!unix:unix-file-kind name)
915                                          :directory))
916                                 (concatenate 'string name "/")
917                                 name)))
918                   (if follow-links (truename name) (pathname name))))
919               (sort (delete-duplicates results :test #'string=) #'string<)))))
920 \f
921 ;;;; translating Unix uid's
922 ;;;;
923 ;;;; FIXME: should probably move into unix.lisp
924
925 (defvar *uid-hash-table* (make-hash-table)
926   #!+sb-doc
927   "hash table for keeping track of uid's and login names")
928
929 (/show0 "filesys.lisp 844")
930
931 ;;; LOOKUP-LOGIN-NAME translates a user id into a login name. Previous
932 ;;; lookups are cached in a hash table since groveling the passwd(s)
933 ;;; files is somewhat expensive. The table may hold NIL for id's that
934 ;;; cannot be looked up since this keeps the files from having to be
935 ;;; searched in their entirety each time this id is translated.
936 (defun lookup-login-name (uid)
937   (multiple-value-bind (login-name foundp) (gethash uid *uid-hash-table*)
938     (if foundp
939         login-name
940         (setf (gethash uid *uid-hash-table*)
941               (get-group-or-user-name :user uid)))))
942
943 ;;; GET-GROUP-OR-USER-NAME first tries "/etc/passwd" ("/etc/group")
944 ;;; since it is a much smaller file, contains all the local id's, and
945 ;;; most uses probably involve id's on machines one would login into.
946 ;;; Then if necessary, we look in "/etc/passwds" ("/etc/groups") which
947 ;;; is really long and has to be fetched over the net.
948 ;;;
949 ;;; FIXME: Now that we no longer have lookup-group-name, we no longer need
950 ;;; the GROUP-OR-USER argument.
951 (defun get-group-or-user-name (group-or-user id)
952   #!+sb-doc
953   "Returns the simple-string user or group name of the user whose uid or gid
954    is id, or NIL if no such user or group exists. Group-or-user is either
955    :group or :user."
956   (let ((id-string (let ((*print-base* 10)) (prin1-to-string id))))
957     (declare (simple-string id-string))
958     (multiple-value-bind (file1 file2)
959         (ecase group-or-user
960           (:group (values "/etc/group" "/etc/groups"))
961           (:user (values "/etc/passwd" "/etc/passwd")))
962       (or (get-group-or-user-name-aux id-string file1)
963           (get-group-or-user-name-aux id-string file2)))))
964
965 ;;; FIXME: Isn't there now a POSIX routine to parse the passwd file?
966 ;;; getpwent? getpwuid?
967 (defun get-group-or-user-name-aux (id-string passwd-file)
968   (with-open-file (stream passwd-file)
969     (loop
970       (let ((entry (read-line stream nil)))
971         (unless entry (return nil))
972         (let ((name-end (position #\: (the simple-string entry)
973                                   :test #'char=)))
974           (when name-end
975             (let ((id-start (position #\: (the simple-string entry)
976                                       :start (1+ name-end) :test #'char=)))
977               (when id-start
978                 (incf id-start)
979                 (let ((id-end (position #\: (the simple-string entry)
980                                         :start id-start :test #'char=)))
981                   (when (and id-end
982                              (string= id-string entry
983                                       :start2 id-start :end2 id-end))
984                     (return (subseq entry 0 name-end))))))))))))
985 \f
986 (/show0 "filesys.lisp 899")
987
988 ;;; Predicate to order pathnames by. Goes by name.
989 (defun pathname-order (x y)
990   (let ((xn (%pathname-name x))
991         (yn (%pathname-name y)))
992     (if (and xn yn)
993         (let ((res (string-lessp xn yn)))
994           (cond ((not res) nil)
995                 ((= res (length (the simple-string xn))) t)
996                 ((= res (length (the simple-string yn))) nil)
997                 (t t)))
998         xn)))
999 \f
1000 (defun default-directory ()
1001   #!+sb-doc
1002   "Returns the pathname for the default directory. This is the place where
1003   a file will be written if no directory is specified. This may be changed
1004   with setf."
1005   (multiple-value-bind (gr dir-or-error) (sb!unix:unix-current-directory)
1006     (if gr
1007         (let ((*ignore-wildcards* t))
1008           (pathname (concatenate 'simple-string dir-or-error "/")))
1009         (error dir-or-error))))
1010
1011 (defun %set-default-directory (new-val)
1012   (let ((namestring (unix-namestring new-val t)))
1013     (unless namestring
1014       (error "~S doesn't exist." new-val))
1015     (multiple-value-bind (gr error) (sb!unix:unix-chdir namestring)
1016       (if gr
1017           (setf (search-list "default:") (default-directory))
1018           (error (sb!unix:get-unix-error-msg error))))
1019     new-val))
1020
1021 (/show0 "filesys.lisp 934")
1022
1023 (/show0 "entering what used to be !FILESYS-COLD-INIT")
1024 (defvar *default-pathname-defaults*
1025   (%make-pathname *unix-host* nil nil nil nil :newest))
1026 (setf (search-list "default:") (default-directory))
1027 (/show0 "leaving what used to be !FILESYS-COLD-INIT")
1028 \f
1029 (defun ensure-directories-exist (pathspec &key verbose (mode #o777))
1030   #!+sb-doc
1031   "Tests whether the directories containing the specified file
1032   actually exist, and attempts to create them if they do not.
1033   Portable programs should avoid using the :MODE argument."
1034   (let* ((pathname (pathname pathspec))
1035          (pathname (if (typep pathname 'logical-pathname)
1036                        (translate-logical-pathname pathname)
1037                        pathname))
1038          (created-p nil))
1039     (when (wild-pathname-p pathname)
1040       (error 'simple-file-error
1041              :format-control "bad place for a wild pathname"
1042              :pathname pathspec))
1043     (enumerate-search-list (pathname pathname)
1044        (let ((dir (pathname-directory pathname)))
1045          (loop for i from 1 upto (length dir)
1046                do (let ((newpath (make-pathname
1047                                   :host (pathname-host pathname)
1048                                   :device (pathname-device pathname)
1049                                   :directory (subseq dir 0 i))))
1050                     (unless (probe-file newpath)
1051                       (let ((namestring (namestring newpath)))
1052                         (when verbose
1053                           (format *standard-output*
1054                                   "~&creating directory: ~A~%"
1055                                   namestring))
1056                         (sb!unix:unix-mkdir namestring mode)
1057                         (unless (probe-file namestring)
1058                           (error 'simple-file-error
1059                                  :pathname pathspec
1060                                  :format-control "can't create directory ~A"
1061                                  :format-arguments (list namestring)))
1062                         (setf created-p t)))))
1063          ;; Only the first path in a search-list is considered.
1064          (return (values pathname created-p))))))
1065
1066 (/show0 "filesys.lisp 1000")