/[cmucl]/src/code/filesys.lisp
ViewVC logotype

Contents of /src/code/filesys.lisp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.16 - (show annotations)
Mon Dec 16 10:31:59 1991 UTC (22 years, 4 months ago) by wlott
Branch: MAIN
Changes since 1.15: +624 -598 lines
Extensive rewrite.  The machine/filesystem independed stuff is now in
pathname.lisp and this file contains basically the Unix depended code.
This rewrite includes full support for wildcards and structured directories
(as per X3J13).  The new pathname format also lends itself better to the
addition of logical pathnames (but they haven't been written, yet).
1 ;;; -*- Log: code.log; Package: Lisp -*-
2 ;;; **********************************************************************
3 ;;; This code was written as part of the CMU Common Lisp project at
4 ;;; Carnegie Mellon University, and has been placed in the public domain.
5 ;;; If you want to use this code or any part of CMU Common Lisp, please contact
6 ;;; Scott Fahlman or slisp-group@cs.cmu.edu.
7 ;;;
8 (ext:file-comment
9 "$Header: /tiger/var/lib/cvsroots/cmucl/src/code/filesys.lisp,v 1.16 1991/12/16 10:31:59 wlott Exp $")
10 ;;;
11 ;;; **********************************************************************
12 ;;;
13 ;;; File system interface functions. This file is pretty UNIX specific.
14 ;;;
15 ;;; Written by William Lott
16 ;;;
17 ;;; **********************************************************************
18
19 (in-package "LISP")
20
21 (export '(truename probe-file user-homedir-pathname directory
22 rename-file delete-file file-write-date file-author))
23
24 (use-package "EXTENSIONS")
25
26 (in-package "EXTENSIONS")
27 (export '(print-directory complete-file ambiguous-files default-directory
28 file-writable unix-namestring))
29 (in-package "LISP")
30
31
32 ;;;; Unix pathname host support.
33
34 ;;; Unix namestrings have the following format:
35 ;;;
36 ;;; namestring := [ directory ] [ file [ type [ version ]]]
37 ;;; directory := [ "/" | search-list ] { file "/" }*
38 ;;; search-list := [^:/]*:
39 ;;; file := [^/]*
40 ;;; type := "." [^/.]*
41 ;;; version := "." ([0-9]+ | "*")
42 ;;;
43 ;;; Note: this grammer is ambiguous. The string foo.bar.5 can be parsed
44 ;;; as either just the file specified or as specifying the file, type, and
45 ;;; version. Therefore, we use the following rules when confronted with
46 ;;; an ambiguous file.type.version string:
47 ;;;
48 ;;; - If the first character is a dot, it's part of the file. It is not
49 ;;; considered a dot in the following rules.
50 ;;;
51 ;;; - If there is only one dot, it seperates the file and the type.
52 ;;;
53 ;;; - If there are multiple dots and the stuff following the last dot
54 ;;; is a valid version, then that is the version and the stuff between
55 ;;; the second to last dot and the last dot is the type.
56 ;;;
57 ;;; Wildcard characters:
58 ;;;
59 ;;; If the directory, file, type components contain any of the following
60 ;;; characters, it is considered part of a wildcard pattern and has the
61 ;;; following meaning.
62 ;;;
63 ;;; ? - matches any character
64 ;;; * - matches any zero or more characters.
65 ;;; [abc] - matches any of a, b, or c.
66 ;;; {str1,str2,...,strn} - matches any of str1, str2, ..., or strn.
67 ;;;
68 ;;; Any of these special characters can be preceeded by a backslash to
69 ;;; cause it to be treated as a regular character.
70 ;;;
71
72 (defun remove-backslashes (namestr start end)
73 "Remove and occurences of \\ from the string because we've already
74 checked for whatever they may have been backslashed."
75 (declare (type simple-base-string namestr)
76 (type index start end))
77 (let* ((result (make-string (- end start)))
78 (dst 0)
79 (quoted nil))
80 (do ((src start (1+ src)))
81 ((= src end))
82 (cond (quoted
83 (setf (schar result dst) (schar namestr src))
84 (setf quoted nil)
85 (incf dst))
86 (t
87 (let ((char (schar namestr src)))
88 (cond ((char= char #\\)
89 (setq quoted t))
90 (t
91 (setf (schar result dst) char)
92 (incf dst)))))))
93 (when quoted
94 (error 'namestring-parse-error
95 :complaint "Backslash in bad place."
96 :namestring namestr
97 :offset (1- end)))
98 (shrink-vector result dst)))
99
100 (defvar *ignore-wildcards* nil)
101
102 (defun maybe-make-pattern (namestr start end)
103 (declare (type simple-base-string namestr)
104 (type index start end))
105 (if *ignore-wildcards*
106 (subseq namestr start end)
107 (collect ((pattern))
108 (let ((quoted nil)
109 (any-quotes nil)
110 (last-regular-char nil)
111 (index start))
112 (flet ((flush-pending-regulars ()
113 (when last-regular-char
114 (pattern (if any-quotes
115 (remove-backslashes namestr
116 last-regular-char
117 index)
118 (subseq namestr last-regular-char index)))
119 (setf any-quotes nil)
120 (setf last-regular-char nil))))
121 (loop
122 (when (>= index end)
123 (return))
124 (let ((char (schar namestr index)))
125 (cond (quoted
126 (incf index)
127 (setf quoted nil))
128 ((char= char #\\)
129 (setf quoted t)
130 (setf any-quotes t)
131 (unless last-regular-char
132 (setf last-regular-char index))
133 (incf index))
134 ((char= char #\?)
135 (flush-pending-regulars)
136 (pattern :single-char-wild)
137 (incf index))
138 ((char= char #\*)
139 (flush-pending-regulars)
140 (pattern :multi-char-wild)
141 (incf index))
142 ((char= char #\[)
143 (flush-pending-regulars)
144 (let ((close-bracket
145 (position #\] namestr :start index :end end)))
146 (unless close-bracket
147 (error 'namestring-parse-error
148 :complaint "``['' with no corresponding ``]''"
149 :namestring namestr
150 :offset index))
151 (pattern (list :character-set
152 (subseq namestr
153 (1+ index)
154 close-bracket)))
155 (setf index (1+ close-bracket))))
156 (t
157 (unless last-regular-char
158 (setf last-regular-char index))
159 (incf index)))))
160 (flush-pending-regulars)))
161 (cond ((null (pattern))
162 "")
163 ((and (null (cdr (pattern)))
164 (simple-string-p (car (pattern))))
165 (car (pattern)))
166 (t
167 (make-pattern (pattern)))))))
168
169 (defun extract-name-type-and-version (namestr start end)
170 (declare (type simple-base-string namestr)
171 (type index start end))
172 (let* ((last-dot (position #\. namestr :start (1+ start) :end end
173 :from-end t))
174 (second-to-last-dot (and last-dot
175 (position #\. namestr :start (1+ start)
176 :end last-dot :from-end t)))
177 (version :newest))
178 ;; If there is a second-to-last dot, check to see if there is a valid
179 ;; version after the last dot.
180 (when second-to-last-dot
181 (cond ((and (= (+ last-dot 2) end)
182 (char= (schar namestr (1+ last-dot)) #\*))
183 (setf version :wild))
184 ((and (< (1+ last-dot) end)
185 (do ((index (1+ last-dot) (1+ index)))
186 ((= index end) t)
187 (unless (char<= #\0 (schar namestr index) #\9)
188 (return nil))))
189 (setf version
190 (parse-integer namestr :start (1+ last-dot) :end end)))
191 (t
192 (setf second-to-last-dot nil))))
193 (cond (second-to-last-dot
194 (values (maybe-make-pattern namestr start second-to-last-dot)
195 (maybe-make-pattern namestr
196 (1+ second-to-last-dot)
197 last-dot)
198 version))
199 (last-dot
200 (values (maybe-make-pattern namestr start last-dot)
201 (maybe-make-pattern namestr (1+ last-dot) end)
202 version))
203 (t
204 (values (maybe-make-pattern namestr start end)
205 nil
206 version)))))
207
208 (defun split-at-slashes (namestr start end)
209 (declare (type simple-base-string namestr)
210 (type index start end))
211 (let ((absolute (and (/= start end)
212 (char= (schar namestr start) #\/))))
213 (when absolute
214 (incf start))
215 ;; Next, split the remainder into slash seperated chunks.
216 (collect ((pieces))
217 (loop
218 (let ((slash (position #\/ namestr :start start :end end)))
219 (pieces (cons start (or slash end)))
220 (unless slash
221 (return))
222 (setf start (1+ slash))))
223 (values absolute (pieces)))))
224
225 (defun maybe-extract-search-list (namestr start end)
226 (declare (type simple-base-string namestr)
227 (type index start end))
228 (let ((quoted nil))
229 (do ((index start (1+ index)))
230 ((= index end)
231 (values nil start))
232 (if quoted
233 (setf quoted nil)
234 (case (schar namestr index)
235 (#\\
236 (setf quoted t))
237 (#\:
238 (return (values (remove-backslashes namestr start index)
239 (1+ index)))))))))
240
241 (defun parse-unix-namestring (namestr start end)
242 (declare (type simple-base-string namestr)
243 (type index start end))
244 (multiple-value-bind
245 (absolute pieces)
246 (split-at-slashes namestr start end)
247 (let ((search-list
248 (if absolute
249 nil
250 (let ((first (car pieces)))
251 (multiple-value-bind
252 (search-list new-start)
253 (maybe-extract-search-list namestr
254 (car first) (cdr first))
255 (when search-list
256 (setf absolute t)
257 (setf (car first) new-start))
258 search-list)))))
259 (multiple-value-bind
260 (name type version)
261 (let* ((tail (car (last pieces)))
262 (tail-start (car tail))
263 (tail-end (cdr tail)))
264 (unless (= tail-start tail-end)
265 (setf pieces (butlast pieces))
266 (extract-name-type-and-version namestr tail-start tail-end)))
267 ;; Now we have everything we want. So return it.
268 (values nil ; no host for unix namestrings.
269 nil ; no devices for unix namestrings.
270 (collect ((dirs))
271 (when search-list
272 (dirs (intern-search-list search-list)))
273 (dolist (piece pieces)
274 (let ((piece-start (car piece))
275 (piece-end (cdr piece)))
276 (unless (= piece-start piece-end)
277 (let ((dir (maybe-make-pattern namestr
278 piece-start
279 piece-end)))
280 (if (and (simple-string-p dir)
281 (string= dir ".."))
282 (dirs :up)
283 (dirs dir))))))
284 (if (dirs)
285 (cons (if absolute :absolute :relative) (dirs))
286 nil))
287 name
288 type
289 version)))))
290
291 (defun unparse-unix-host (pathname)
292 (declare (type pathname pathname)
293 (ignore pathname))
294 "Unix")
295
296 (defun unparse-unix-piece (thing)
297 (etypecase thing
298 (simple-string
299 (let* ((srclen (length thing))
300 (dstlen srclen))
301 (dotimes (i srclen)
302 (case (schar thing i)
303 ((#\* #\? #\[)
304 (incf dstlen))))
305 (let ((result (make-string dstlen))
306 (dst 0))
307 (dotimes (src srclen)
308 (let ((char (schar thing src)))
309 (case char
310 ((#\* #\? #\[)
311 (setf (schar result dst) #\\)
312 (incf dst)))
313 (setf (schar result dst) char)
314 (incf dst)))
315 result)))
316 (pattern
317 (collect ((strings))
318 (dolist (piece (pattern-pieces thing))
319 (etypecase piece
320 (simple-string
321 (strings piece))
322 (symbol
323 (case piece
324 (:multi-char-wild
325 (strings "*"))
326 (:single-char-wild
327 (strings "?"))
328 (t
329 (error "Invalid pattern piece: ~S" piece))))
330 (cons
331 (case (car piece)
332 (:character-set
333 (strings "[")
334 (strings (cdr piece))
335 (strings "]"))
336 (t
337 (error "Invalid pattern piece: ~S" piece))))))
338 (apply #'concatenate
339 'simple-string
340 (strings))))))
341
342 (defun unparse-unix-directory-list (directory)
343 (declare (type list directory))
344 (collect ((pieces))
345 (when directory
346 (ecase (pop directory)
347 (:absolute
348 (cond ((search-list-p (car directory))
349 (pieces (search-list-name (pop directory)))
350 (pieces ":"))
351 (t
352 (pieces "/"))))
353 (:relative
354 ;; Nothing special.
355 ))
356 (dolist (dir directory)
357 (typecase dir
358 ((member :up)
359 (pieces "../"))
360 ((member :back)
361 (error ":BACK cannot be represented in namestrings."))
362 ((or simple-string pattern)
363 (pieces (unparse-unix-piece dir))
364 (pieces "/"))
365 (t
366 (error "Invalid directory component: ~S" dir)))))
367 (apply #'concatenate 'simple-string (pieces))))
368
369 (defun unparse-unix-directory (pathname)
370 (declare (type pathname pathname))
371 (unparse-unix-directory-list (%pathname-directory pathname)))
372
373 (defun unparse-unix-file (pathname)
374 (declare (type pathname pathname))
375 (collect ((strings))
376 (let* ((name (%pathname-name pathname))
377 (type (%pathname-type pathname))
378 (type-supplied (not (or (null type) (eq type :unspecific))))
379 (version (%pathname-version pathname))
380 (version-supplied (not (or (null version) (eq version :newest)))))
381 (when name
382 (strings (unparse-unix-piece name)))
383 (when type-supplied
384 (unless name
385 (error "Cannot specify the type without a file: ~S" pathname))
386 (strings ".")
387 (strings (unparse-unix-piece type)))
388 (when version-supplied
389 (unless type-supplied
390 (error "Cannot specify the version without a type: ~S" pathname))
391 (strings (if (eq version :wild)
392 ".*"
393 (format nil ".~D" version)))))
394 (apply #'concatenate 'simple-string (strings))))
395
396 (defun unparse-unix-namestring (pathname)
397 (declare (type pathname pathname))
398 (concatenate 'simple-string
399 (unparse-unix-directory pathname)
400 (unparse-unix-file pathname)))
401
402 (defun unparse-unix-enough (pathname defaults)
403 (declare (type pathname pathname defaults))
404 (flet ((lose ()
405 (error "~S cannot be represented relative to ~S"
406 pathname defaults)))
407 (collect ((strings))
408 (let* ((pathname-directory (%pathname-directory pathname))
409 (defaults-directory (%pathname-directory defaults))
410 (prefix-len (length defaults-directory))
411 (result-dir
412 (cond ((and (> prefix-len 1)
413 (>= (length pathname-directory) prefix-len)
414 (compare-component (subseq pathname-directory
415 0 prefix-len)
416 defaults-directory))
417 ;; Pathname starts with a prefix of default. So just
418 ;; use a relative directory from then on out.
419 (cons :relative (nthcdr prefix-len pathname-directory)))
420 ((eq (car pathname-directory) :absolute)
421 ;; We are an absolute pathname, so we can just use it.
422 pathname-directory)
423 (t
424 ;; We are a relative directory. So we lose.
425 (lose)))))
426 (strings (unparse-unix-directory-list result-dir)))
427 (let* ((pathname-version (%pathname-version pathname))
428 (version-needed (and pathname-version
429 (not (eq pathname-version :newest))))
430 (pathname-type (%pathname-type pathname))
431 (type-needed (or version-needed
432 (and pathname-type
433 (not (eq pathname-type :unspecific)))))
434 (pathname-name (%pathname-name pathname))
435 (name-needed (or type-needed
436 (and pathname-name
437 (not (compare-component pathname-name
438 (%pathname-name
439 defaults)))))))
440 (when name-needed
441 (unless pathname-name (lose))
442 (strings (unparse-unix-piece pathname-name)))
443 (when type-needed
444 (when (or (null pathname-type) (eq pathname-type :unspecific))
445 (lose))
446 (strings ".")
447 (strings (unparse-unix-piece pathname-type)))
448 (when version-needed
449 (typecase pathname-version
450 ((member :wild)
451 (strings ".*"))
452 (integer
453 (strings (format nil ".~D" pathname-version)))
454 (t
455 (lose)))))
456 (apply #'concatenate 'simple-string (strings)))))
457
458
459 (defstruct (unix-host
460 (:include host
461 (:parse #'parse-unix-namestring)
462 (:unparse #'unparse-unix-namestring)
463 (:unparse-host #'unparse-unix-host)
464 (:unparse-directory #'unparse-unix-directory)
465 (:unparse-file #'unparse-unix-file)
466 (:unparse-enough #'unparse-unix-enough)
467 (:customary-case :lower))
468 (:make-load-form-fun make-unix-host-load-form))
469 )
470
471 (defvar *unix-host* (make-unix-host))
472
473 (defun make-unix-host-load-form (host)
474 (declare (ignore host))
475 '*unix-host*)
476
477
478 ;;;; Wildcard matching stuff.
479
480 (defmacro enumerate-matches ((var pathname &optional result
481 &key (verify-existance t))
482 &body body)
483 (let ((body-name (gensym)))
484 `(block nil
485 (flet ((,body-name (,var)
486 ,@body))
487 (%enumerate-matches (pathname ,pathname)
488 ,verify-existance
489 #',body-name)
490 ,result))))
491
492 (defun %enumerate-matches (pathname verify-existance function)
493 (when (pathname-type pathname)
494 (unless (pathname-name pathname)
495 (error "Cannot supply a type without a name:~% ~S" pathname)))
496 (when (and (integerp (pathname-version pathname))
497 (member (pathname-type pathname) '(nil :unspecific)))
498 (error "Cannot supply a version without a type:~% ~S" pathname))
499 (let ((directory (pathname-directory pathname)))
500 (if directory
501 (ecase (car directory)
502 (:absolute
503 (%enumerate-directories "/" (cdr directory) pathname
504 verify-existance function))
505 (:relative
506 (%enumerate-directories "" (cdr directory) pathname
507 verify-existance function)))
508 (%enumerate-files "" pathname verify-existance function))))
509
510 (defun %enumerate-directories (head tail pathname verify-existance function)
511 (if tail
512 (let ((piece (car tail)))
513 (etypecase piece
514 (simple-string
515 (%enumerate-directories (concatenate 'string head piece "/")
516 (cdr tail) pathname verify-existance
517 function))
518 (pattern
519 (let ((dir (mach:open-dir head)))
520 (when dir
521 (unwind-protect
522 (loop
523 (let ((name (mach:read-dir dir)))
524 (cond ((null name)
525 (return))
526 ((string= name "."))
527 ((string= name ".."))
528 ((pattern-matches piece name)
529 (let ((subdir (concatenate 'string
530 head name "/")))
531 (when (eq (mach:unix-file-kind subdir)
532 :directory)
533 (%enumerate-directories
534 subdir (cdr tail) pathname verify-existance
535 function)))))))
536 (mach:close-dir dir)))))
537 ((member :up)
538 (%enumerate-directories (concatenate 'string head "../")
539 (cdr tail) pathname verify-existance
540 function))))
541 (%enumerate-files head pathname verify-existance function)))
542
543 (defun %enumerate-files (directory pathname verify-existance function)
544 (let ((name (pathname-name pathname))
545 (type (pathname-type pathname))
546 (version (pathname-version pathname)))
547 (cond ((null name)
548 (when (or (not verify-existance)
549 (mach:unix-file-kind directory))
550 (funcall function directory)))
551 ((or (pattern-p name)
552 (pattern-p type)
553 (eq version :wild))
554 (let ((dir (mach:open-dir directory)))
555 (when dir
556 (unwind-protect
557 (loop
558 (let ((file (mach:read-dir dir)))
559 (if file
560 (multiple-value-bind
561 (file-name file-type file-version)
562 (let ((*ignore-wildcards* t))
563 (extract-name-type-and-version
564 file 0 (length file)))
565 (when (and (components-match file-name name)
566 (components-match file-type type)
567 (components-match file-version
568 version))
569 (funcall function
570 (concatenate 'string
571 directory
572 file))))
573 (return))))
574 (mach:close-dir dir)))))
575 (t
576 (let ((file (concatenate 'string directory name)))
577 (unless (eq type :unspecific)
578 (setf file (concatenate 'string file "." type)))
579 (unless (eq version :newest)
580 (setf file (concatenate 'string file "."
581 (quick-integer-to-string version))))
582 (when (or (not verify-existance)
583 (mach:unix-file-kind file))
584 (funcall function file)))))))
585
586 (defun quick-integer-to-string (n)
587 (declare (type integer n))
588 (cond ((zerop n) "0")
589 ((eql n 1) "1")
590 ((minusp n)
591 (concatenate 'simple-string "-"
592 (the simple-string (quick-integer-to-string (- n)))))
593 (t
594 (do* ((len (1+ (truncate (integer-length n) 3)))
595 (res (make-string len))
596 (i (1- len) (1- i))
597 (q n)
598 (r 0))
599 ((zerop q)
600 (incf i)
601 (replace res res :start2 i :end2 len)
602 (shrink-vector res (- len i)))
603 (declare (simple-string res)
604 (fixnum len i r))
605 (multiple-value-setq (q r) (truncate q 10))
606 (setf (schar res i) (schar "0123456789" r))))))
607
608
609 ;;;; UNIX-NAMESTRING -- public
610 ;;;
611 (defun unix-namestring (pathname &optional (for-input t))
612 "Convert PATHNAME into a string that can be used with UNIX system calls.
613 Search-lists and wild-cards are expanded."
614 (enumerate-search-list
615 (pathname pathname)
616 (collect ((names))
617 (enumerate-matches (name pathname nil :verify-existance for-input)
618 (names name))
619 (let ((names (names)))
620 (when names
621 (when (cdr names)
622 (error "~S is ambiguous:~{~% ~A~}" pathname names))
623 (return (car names)))))))
624
625
626 ;;;; TRUENAME and PROBE-FILE.
627
628 ;;; Truename -- Public
629 ;;;
630 ;;; Another silly file function trivially different from another function.
631 ;;;
632 (defun truename (pathname)
633 "Return the pathname for the actual file described by the pathname
634 An error is signalled if no such file exists."
635 (let ((result (probe-file pathname)))
636 (unless result
637 (error "The file ~S does not exist." (namestring pathname)))
638 result))
639
640 ;;; Probe-File -- Public
641 ;;;
642 ;;; If PATHNAME exists, return it's truename, otherwise NIL.
643 ;;;
644 (defun probe-file (pathname)
645 "Return a pathname which is the truename of the file if it exists, NIL
646 otherwise."
647 (let ((namestring (unix-namestring pathname t)))
648 (when (and namestring (mach:unix-file-kind namestring))
649 (let ((truename (mach:unix-resolve-links
650 (mach:unix-maybe-prepend-current-directory
651 namestring))))
652 (when truename
653 (let ((*ignore-wildcards* t))
654 (pathname (mach:unix-simplify-pathname truename))))))))
655
656
657 ;;;; Other random operations.
658
659 ;;; Rename-File -- Public
660 ;;;
661 (defun rename-file (file new-name)
662 "Rename File to have the specified New-Name. If file is a stream open to a
663 file, then the associated file is renamed. If the file does not yet exist
664 then the file is created with the New-Name when the stream is closed."
665 (let* ((original (truename file))
666 (original-namestring (unix-namestring original t))
667 (new-name (merge-pathnames new-name original))
668 (new-namestring (unix-namestring new-name nil)))
669 (multiple-value-bind (res error)
670 (mach:unix-rename original-namestring
671 new-namestring)
672 (unless res
673 (error "Failed to rename ~A to ~A: ~A"
674 original new-name (mach:get-unix-error-msg error)))
675 (when (streamp file)
676 (file-name file new-namestring))
677 (values new-name original (truename new-name)))))
678
679 ;;; Delete-File -- Public
680 ;;;
681 ;;; Delete the file, Man.
682 ;;;
683 (defun delete-file (file)
684 "Delete the specified file."
685 (let ((namestring (unix-namestring file t)))
686 (when (streamp file)
687 (close file :abort t))
688 (when namestring
689 (multiple-value-bind (res err) (mach:unix-unlink namestring)
690 (unless res
691 (error "Could not delete ~A: ~A."
692 namestring
693 (mach:get-unix-error-msg err))))))
694 t)
695
696
697 ;;; User-Homedir-Pathname -- Public
698 ;;;
699 ;;; Return Home:, which is set up for us at initialization time.
700 ;;;
701 (defun user-homedir-pathname (&optional host)
702 "Returns the home directory of the logged in user as a pathname.
703 This is obtained from the logical name \"home:\"."
704 (declare (ignore host))
705 #p"home:")
706
707 ;;; File-Write-Date -- Public
708 ;;;
709 (defun file-write-date (file)
710 "Return file's creation date, or NIL if it doesn't exist."
711 (multiple-value-bind (res dev ino mode nlink uid gid
712 rdev size atime mtime)
713 (mach:unix-stat (unix-namestring file t))
714 (declare (ignore dev ino mode nlink uid gid rdev size atime))
715 (when res
716 (+ unix-to-universal-time mtime))))
717
718 ;;; File-Author -- Public
719 ;;;
720 (defun file-author (file)
721 "Returns the file author as a string, or nil if the author cannot be
722 determined. Signals an error if file doesn't exist."
723 (multiple-value-bind (winp dev ino mode nlink uid)
724 (mach:unix-stat (unix-namestring (pathname file) t))
725 (declare (ignore dev ino mode nlink))
726 (if winp (lookup-login-name uid))))
727
728
729
730 ;;;; DIRECTORY.
731
732 ;;; DIRECTORY -- public.
733 ;;;
734 (defun directory (pathname &key (all t) (check-for-subdirs t))
735 "Returns a list of pathnames, one for each file that matches the given
736 pathname. Supplying :all as nil causes this to ignore Unix dot files. This
737 never includes Unix dot and dot-dot in the result."
738 (let ((results nil))
739 (enumerate-search-list
740 (pathname pathname)
741 (enumerate-matches (name pathname)
742 (when (or all
743 (let ((slash (position #\/ name :from-end t)))
744 (or (null slash)
745 (= (1+ slash) (length name))
746 (char/= (schar name (1+ slash)) #\.))))
747 (push name results))))
748 (let ((*ignore-wildcards* t))
749 (mapcar #'(lambda (name)
750 (if (and check-for-subdirs
751 (eq (mach:unix-file-kind name) :directory))
752 (pathname (concatenate 'string name "/"))
753 (pathname name)))
754 (sort (delete-duplicates results :test #'string=) #'string<)))))
755
756
757 ;;;; Printing directories.
758
759 ;;; PRINT-DIRECTORY is exported from the EXTENSIONS package.
760 ;;;
761 (defun print-directory (pathname &optional stream &key all verbose return-list)
762 "Like Directory, but prints a terse, multi-coloumn directory listing
763 instead of returning a list of pathnames. When :all is supplied and
764 non-nil, then Unix dot files are included too (as ls -a). When :vervose
765 is supplied and non-nil, then a long listing of miscellaneous
766 information is output one file per line."
767 (let ((*standard-output* (out-synonym-of stream))
768 (pathname pathname))
769 (if verbose
770 (print-directory-verbose pathname all return-list)
771 (print-directory-formatted pathname all return-list))))
772
773 (defun print-directory-verbose (pathname all return-list)
774 (let ((contents (directory pathname :all all :check-for-subdirs nil))
775 (result nil))
776 (format t "Directory of ~A :~%" (namestring pathname))
777 (dolist (file contents)
778 (let* ((namestring (unix-namestring file))
779 (tail (subseq namestring
780 (1+ (or (position #\/ namestring
781 :from-end t
782 :test #'char=)
783 -1)))))
784 (multiple-value-bind
785 (reslt dev-or-err ino mode nlink uid gid rdev size atime mtime)
786 (mach:unix-stat namestring)
787 (declare (ignore ino gid rdev atime)
788 (fixnum uid mode))
789 (cond (reslt
790 ;;
791 ;; Print characters for file modes.
792 (macrolet ((frob (bit name &optional sbit sname negate)
793 `(if ,(if negate
794 `(not (logbitp ,bit mode))
795 `(logbitp ,bit mode))
796 ,(if sbit
797 `(if (logbitp ,sbit mode)
798 (write-char ,sname)
799 (write-char ,name))
800 `(write-char ,name))
801 (write-char #\-))))
802 (frob 15 #\d nil nil t)
803 (frob 8 #\r)
804 (frob 7 #\w)
805 (frob 6 #\x 11 #\s)
806 (frob 5 #\r)
807 (frob 4 #\w)
808 (frob 3 #\x 10 #\s)
809 (frob 2 #\r)
810 (frob 1 #\w)
811 (frob 0 #\x))
812 ;;
813 ;; Print the rest.
814 (multiple-value-bind (sec min hour date month year)
815 (get-decoded-time)
816 (declare (ignore sec min hour date month))
817 (format t "~2D ~8A ~8D ~12A ~A~@[/~]~%"
818 nlink
819 (or (lookup-login-name uid) uid)
820 size
821 (decode-universal-time-for-files mtime year)
822 tail
823 (= (logand mode mach::s_ifmt) mach::s_ifdir))))
824 (t (format t "Couldn't stat ~A -- ~A.~%"
825 tail
826 (mach:get-unix-error-msg dev-or-err))))
827 (when return-list
828 (push (if (= (logand mode mach::s_ifmt) mach::s_ifdir)
829 (pathname (concatenate 'string namestring "/"))
830 file)
831 result)))))
832 (nreverse result)))
833
834 (defun decode-universal-time-for-files (time current-year)
835 (multiple-value-bind (sec min hour day month year)
836 (decode-universal-time (+ time unix-to-universal-time))
837 (declare (ignore sec))
838 (format nil "~A ~2,' D ~:[ ~D~;~*~2,'0D:~2,'0D~]"
839 (svref '#("Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug"
840 "Sep" "Oct" "Nov" "Dec")
841 (1- month))
842 day (= current-year year) year hour min)))
843
844 (defun print-directory-formatted (pathname all return-list)
845 (let ((width (or (line-length *standard-output*) 80))
846 (names ())
847 (cnt 0)
848 (max-len 0)
849 (result (directory pathname :all all)))
850 (declare (list names) (fixnum max-len cnt))
851 ;;
852 ;; Get the data.
853 (dolist (file result)
854 (let* ((name (unix-namestring file))
855 (length (length name))
856 (end (if (and (plusp length)
857 (char= (schar name (1- length)) #\/))
858 (1- length)
859 length))
860 (slash-name (subseq name
861 (1+ (or (position #\/ name
862 :from-end t
863 :end end
864 :test #'char=)
865 -1))))
866 (len (length slash-name)))
867 (declare (simple-string slash-name)
868 (fixnum len))
869 (if (> len max-len) (setq max-len len))
870 (incf cnt)
871 (push slash-name names)))
872 (setq names (nreverse names))
873 ;;
874 ;; Do the output.
875 (let* ((col-width (1+ max-len))
876 (cols (max (truncate width col-width) 1))
877 (lines (ceiling cnt cols)))
878 (declare (fixnum cols lines))
879 (format t "Directory of ~A :~%" (namestring pathname))
880 (dotimes (i lines)
881 (declare (fixnum i))
882 (dotimes (j cols)
883 (declare (fixnum j))
884 (let ((name (nth (+ i (the fixnum (* j lines))) names)))
885 (when name
886 (write-string name)
887 (unless (eql j (1- cols))
888 (dotimes (i (- col-width (length (the simple-string name))))
889 (write-char #\space))))))
890 (terpri)))
891 (when return-list
892 result)))
893
894
895
896 ;;;; Translating uid's and gid's.
897
898 (defvar *uid-hash-table* (make-hash-table)
899 "Hash table for keeping track of uid's and login names.")
900
901 ;;; LOOKUP-LOGIN-NAME translates a user id into a login name. Previous
902 ;;; lookups are cached in a hash table since groveling the passwd(s) files
903 ;;; is somewhat expensive. The table may hold nil for id's that cannot
904 ;;; be looked up since this means the files are searched in their entirety
905 ;;; each time this id is translated.
906 ;;;
907 (defun lookup-login-name (uid)
908 (multiple-value-bind (login-name foundp) (gethash uid *uid-hash-table*)
909 (if foundp
910 login-name
911 (setf (gethash uid *uid-hash-table*)
912 (get-group-or-user-name :user uid)))))
913
914 (defvar *gid-hash-table* (make-hash-table)
915 "Hash table for keeping track of gid's and group names.")
916
917 ;;; LOOKUP-GROUP-NAME translates a group id into a group name. Previous
918 ;;; lookups are cached in a hash table since groveling the group(s) files
919 ;;; is somewhat expensive. The table may hold nil for id's that cannot
920 ;;; be looked up since this means the files are searched in their entirety
921 ;;; each time this id is translated.
922 ;;;
923 (defun lookup-group-name (gid)
924 (multiple-value-bind (group-name foundp) (gethash gid *gid-hash-table*)
925 (if foundp
926 group-name
927 (setf (gethash gid *gid-hash-table*)
928 (get-group-or-user-name :group gid)))))
929
930
931 ;;; GET-GROUP-OR-USER-NAME first tries "/etc/passwd" ("/etc/group") since it is
932 ;;; a much smaller file, contains all the local id's, and most uses probably
933 ;;; involve id's on machines one would login into. Then if necessary, we look
934 ;;; in "/etc/passwds" ("/etc/groups") which is really long and has to be
935 ;;; fetched over the net.
936 ;;;
937 (defun get-group-or-user-name (group-or-user id)
938 "Returns the simple-string user or group name of the user whose uid or gid
939 is id, or NIL if no such user or group exists. Group-or-user is either
940 :group or :user."
941 (let ((id-string (let ((*print-base* 10)) (prin1-to-string id))))
942 (declare (simple-string id-string))
943 (multiple-value-bind (file1 file2)
944 (ecase group-or-user
945 (:group (values "/etc/group" "/etc/groups"))
946 (:user (values "/etc/passwd" "/etc/passwd")))
947 (or (get-group-or-user-name-aux id-string file1)
948 (get-group-or-user-name-aux id-string file2)))))
949
950 (defun get-group-or-user-name-aux (id-string passwd-file)
951 (with-open-file (stream passwd-file)
952 (loop
953 (let ((entry (read-line stream nil)))
954 (unless entry (return nil))
955 (let ((name-end (position #\: (the simple-string entry)
956 :test #'char=)))
957 (when name-end
958 (let ((id-start (position #\: (the simple-string entry)
959 :start (1+ name-end) :test #'char=)))
960 (when id-start
961 (incf id-start)
962 (let ((id-end (position #\: (the simple-string entry)
963 :start id-start :test #'char=)))
964 (when (and id-end
965 (string= id-string entry
966 :start2 id-start :end2 id-end))
967 (return (subseq entry 0 name-end))))))))))))
968
969
970 ;;;; File completion.
971
972 ;;; COMPLETE-FILE -- Public
973 ;;;
974 (defun complete-file (pathname &key (defaults *default-pathname-defaults*)
975 ignore-types)
976 (let ((files
977 (directory (complete-file-directory-arg pathname defaults)
978 :check-for-subdirs nil)))
979 (cond ((null files)
980 (values nil nil))
981 ((null (cdr files))
982 (values (merge-pathnames (file-namestring (car files))
983 pathname)
984 t))
985 (t
986 (let ((good-files
987 (delete-if #'(lambda (pathname)
988 (and (simple-string-p
989 (pathname-type pathname))
990 (member (pathname-type pathname)
991 ignore-types
992 :test #'string=)))
993 files)))
994 (cond ((null good-files))
995 ((null (cdr good-files))
996 (return-from complete-file
997 (values (merge-pathnames (file-namestring
998 (car good-files))
999 pathname)
1000 t)))
1001 (t
1002 (setf files good-files)))
1003 (let ((common (file-namestring (car files))))
1004 (dolist (file (cdr files))
1005 (let ((name (file-namestring file)))
1006 (dotimes (i (min (length common) (length name))
1007 (when (< (length name) (length common))
1008 (setf common name)))
1009 (unless (char= (schar common i) (schar name i))
1010 (setf common (subseq common 0 i))
1011 (return)))))
1012 (values (merge-pathnames common pathname)
1013 nil)))))))
1014
1015 ;;; COMPLETE-FILE-DIRECTORY-ARG -- Internal.
1016 ;;;
1017 (defun complete-file-directory-arg (pathname defaults)
1018 (let* ((pathname (merge-pathnames pathname defaults))
1019 (type (pathname-type pathname)))
1020 (flet ((append-multi-char-wild (thing)
1021 (etypecase thing
1022 (null :wild)
1023 (pattern
1024 (make-pattern (append (pattern-pieces thing)
1025 (list :multi-char-wild))))
1026 (simple-string
1027 (make-pattern (list thing :multi-char-wild))))))
1028 (if (or (null type) (eq type :unspecific))
1029 ;; There is no type.
1030 (make-pathname :defaults pathname
1031 :name (append-multi-char-wild (pathname-name pathname))
1032 :type :wild)
1033 ;; There already is a type, so just extend it.
1034 (make-pathname :defaults pathname
1035 :name (pathname-name pathname)
1036 :type (append-multi-char-wild (pathname-type pathname)))))))
1037
1038 ;;; Ambiguous-Files -- Public
1039 ;;;
1040 (defun ambiguous-files (pathname
1041 &optional (defaults *default-pathname-defaults*))
1042 "Return a list of all files which are possible completions of Pathname.
1043 We look in the directory specified by Defaults as well as looking down
1044 the search list."
1045 (directory (complete-file-directory-arg pathname defaults)
1046 :check-for-subdirs nil))
1047
1048
1049
1050 ;;; File-writable -- exported from extensions.
1051 ;;;
1052 ;;; Determines whether the single argument (which should be a pathname)
1053 ;;; can be written by the the current task.
1054 ;;;
1055 (defun file-writable (name)
1056 "File-writable accepts a pathname and returns T if the current
1057 process can write it, and NIL otherwise."
1058 (let ((name (unix-namestring name nil)))
1059 (values
1060 (if (mach:unix-file-kind name)
1061 (mach:unix-access name mach:w_ok)
1062 (mach:unix-access (subseq name
1063 0
1064 (or (position #\/ name :from-end t)
1065 0))
1066 (logior mach:w_ok mach:x_ok))))))
1067
1068
1069 ;;; Pathname-Order -- Internal
1070 ;;;
1071 ;;; Predicate to order pathnames by. Goes by name.
1072 ;;;
1073 (defun pathname-order (x y)
1074 (let ((xn (%pathname-name x))
1075 (yn (%pathname-name y)))
1076 (if (and xn yn)
1077 (let ((res (string-lessp xn yn)))
1078 (cond ((not res) nil)
1079 ((= res (length (the simple-string xn))) t)
1080 ((= res (length (the simple-string yn))) nil)
1081 (t t)))
1082 xn)))
1083
1084
1085 ;;; Default-Directory -- Public
1086 ;;;
1087 (defun default-directory ()
1088 "Returns the pathname for the default directory. This is the place where
1089 a file will be written if no directory is specified. This may be changed
1090 with setf."
1091 (multiple-value-bind (gr dir-or-error)
1092 (mach:unix-current-directory)
1093 (if gr
1094 (let ((*ignore-wildcards* t))
1095 (pathname (concatenate 'simple-string dir-or-error "/")))
1096 (error dir-or-error))))
1097
1098 ;;; %Set-Default-Directory -- Internal
1099 ;;;
1100 (defun %set-default-directory (new-val)
1101 (multiple-value-bind (gr error)
1102 (mach:unix-chdir (unix-namestring new-val t))
1103 (if gr
1104 (setf (search-list "default:") (default-directory))
1105 (error (mach:get-unix-error-msg error))))
1106 new-val)
1107 ;;;
1108 (defsetf default-directory %set-default-directory)
1109
1110 (defun filesys-init ()
1111 (setf *default-pathname-defaults*
1112 (%make-pathname *unix-host* nil nil nil nil :newest))
1113 (setf (search-list "default:") (default-directory))
1114 nil)

  ViewVC Help
Powered by ViewVC 1.1.5