pathname.lisp 49.9 KB
Newer Older
1
2
3
4
5
;;;; -------------------------------------------------------------------------
;;;; Portability layer around Common Lisp pathnames

(asdf/package:define-package :asdf/pathname
  (:recycle :asdf/pathname :asdf)
6
  #+gcl<2.7 (:shadowing-import-from :system :*load-pathname*) ;; GCL 2.6 sucks
7
  (:use :common-lisp :asdf/package :asdf/compatibility :asdf/utility)
8
9
10
11
  (:export
   #:*resolve-symlinks*
   ;; Making and merging pathnames, portably
   #:normalize-pathname-directory-component #:denormalize-pathname-directory-component
12
   #:pathname-equal
13
   #:merge-pathname-directory-components #:make-pathname* #:*unspecific-pathname-type*
14
15
16
17
18
19
   #:make-pathname-component-logical #:make-pathname-logical
   #:merge-pathnames*
   ;; Directories
   #:pathname-directory-pathname #:pathname-parent-directory-pathname
   #:directory-pathname-p #:ensure-directory-pathname
   ;; Absolute vs relative pathnames
20
   #:ensure-pathname-absolute
21
22
23
   #:relativize-directory-component #:relativize-pathname-directory
   ;; Parsing filenames and lists thereof
   #:component-name-to-pathname-components
24
   #:split-name-type #:parse-unix-namestring #:unix-namestring
25
   #:split-unix-namestring-directory-components
26
   #:subpathname #:subpathname*
27
28
29
30
31
   ;; Resolving symlinks somewhat
   #:truenamize #:resolve-symlinks #:resolve-symlinks*
   ;; Wildcard pathnames
   #:*wild* #:*wild-file* #:*wild-directory* #:*wild-inferiors* #:*wild-path* #:wilden
   ;; Pathname host and its root
32
   #:absolute-pathname-p #:relative-pathname-p #:hidden-pathname-p
33
   #:pathname-root #:directory-separator-for-host
34
   #:directorize-pathname-host-device
35
36
   ;; defaults
   #:nil-pathname #:with-pathname-defaults
37
   ;; probe filesystem
38
   #:truename* #:probe-file* #:safe-file-write-date
39
40
41
42
43
44
45
46
   #:subdirectories #:directory-files #:directory*
   #:filter-logical-directory-results #:collect-sub*directories
   ;; Simple filesystem operations
   #:ensure-all-directories-exist
   #:rename-file-overwriting-target
   #:delete-file-if-exists
   ;; Translate a pathname
   #:translate-pathname*
47
   ;; temporary
48
49
   #:add-pathname-suffix #:tmpize-pathname
   #:call-with-staging-pathname #:with-staging-pathname
50
   ;; physical pathnames
51
   #:physical-pathname-p #:sane-physical-pathname #:root-pathname
52
53
   ;; Windows shortcut support
   #:read-null-terminated-string #:read-little-endian
54
   #:parse-file-location-info #:parse-windows-shortcut
55
56
   ;; Checking constraints
   #:ensure-pathname
57
   ;; Output translations
58
   #:*output-translation-function*))
59

60
61
62
63
64
65
66
67
(in-package :asdf/pathname)

;;; User-visible parameters
(defvar *resolve-symlinks* t
  "Determine whether or not ASDF resolves symlinks when defining systems.

Defaults to T.")

68

69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
;;; The hell of portably making and merging pathnames!

(defun* normalize-pathname-directory-component (directory)
  "Given a pathname directory component, return an equivalent form that is a list"
  #+gcl<2.7 (setf directory (substitute :back :parent directory))
  (cond
    #-(or cmu sbcl scl) ;; these implementations already normalize directory components.
    ((stringp directory) `(:absolute ,directory))
    #+gcl<2.7
    ((and (consp directory) (eq :root (first directory)))
     `(:absolute ,@(rest directory)))
    ((or (null directory)
         (and (consp directory) (member (first directory) '(:absolute :relative))))
     directory)
    #+gcl<2.7
    ((consp directory)
     `(:relative ,@directory))
    (t
     (error (compatfmt "~@<Unrecognized pathname directory component ~S~@:>") directory))))

(defun* denormalize-pathname-directory-component (directory-component)
  #-gcl<2.7 directory-component
  #+gcl<2.7
  (let ((d (substitute-if :parent (lambda (x) (member x '(:up :back)))
                          directory-component)))
    (cond
      ((and (consp d) (eq :relative (first d))) (rest d))
      ((and (consp d) (eq :absolute (first d))) `(:root ,@(rest d)))
      (t d))))

(defun* merge-pathname-directory-components (specified defaults)
  ;; Helper for merge-pathnames* that handles directory components.
  (let ((directory (normalize-pathname-directory-component specified)))
    (ecase (first directory)
      ((nil) defaults)
      (:absolute specified)
      (:relative
       (let ((defdir (normalize-pathname-directory-component defaults))
             (reldir (cdr directory)))
         (cond
           ((null defdir)
            directory)
           ((not (eq :back (first reldir)))
            (append defdir reldir))
           (t
            (loop :with defabs = (first defdir)
              :with defrev = (reverse (rest defdir))
              :while (and (eq :back (car reldir))
                          (or (and (eq :absolute defabs) (null defrev))
                              (stringp (car defrev))))
              :do (pop reldir) (pop defrev)
              :finally (return (cons defabs (append (reverse defrev) reldir)))))))))))

122
123
124
125
126
127
128
;; Giving :unspecific as :type argument to make-pathname is not portable.
;; See CLHS make-pathname and 19.2.2.2.3.
;; This will be :unspecific if supported, or NIL if not.
(defparameter *unspecific-pathname-type*
  #+(or abcl allegro clozure cmu gcl genera lispworks mkcl sbcl scl xcl) :unspecific
  #+(or clisp ecl #|These haven't been tested:|# cormanlisp mcl) nil)

129
(defun* make-pathname* (&rest keys &key (directory nil directoryp)
130
131
                              host (device () devicep) name type version defaults
                              #+scl &allow-other-keys)
132
133
134
  "Takes arguments like CL:MAKE-PATHNAME in the CLHS, and
   tries hard to make a pathname that will actually behave as documented,
   despite the peculiarities of each implementation"
135
  (declare (ignorable host device devicep name type version defaults))
136
  (apply 'make-pathname
137
         (append
Francois-Rene Rideau's avatar
Francois-Rene Rideau committed
138
          #+allegro (when (and devicep (null device)) `(:device :unspecific))
139
140
141
          (when directoryp
            `(:directory ,(denormalize-pathname-directory-component directory)))
          keys)))
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166

(defun* make-pathname-component-logical (x)
  "Make a pathname component suitable for use in a logical-pathname"
  (typecase x
    ((eql :unspecific) nil)
    #+clisp (string (string-upcase x))
    #+clisp (cons (mapcar 'make-pathname-component-logical x))
    (t x)))

(defun* make-pathname-logical (pathname host)
  "Take a PATHNAME's directory, name, type and version components,
and make a new pathname with corresponding components and specified logical HOST"
  (make-pathname*
   :host host
   :directory (make-pathname-component-logical (pathname-directory pathname))
   :name (make-pathname-component-logical (pathname-name pathname))
   :type (make-pathname-component-logical (pathname-type pathname))
   :version (make-pathname-component-logical (pathname-version pathname))))

(defun* merge-pathnames* (specified &optional (defaults *default-pathname-defaults*))
  "MERGE-PATHNAMES* is like MERGE-PATHNAMES except that
if the SPECIFIED pathname does not have an absolute directory,
then the HOST and DEVICE both come from the DEFAULTS, whereas
if the SPECIFIED pathname does have an absolute directory,
then the HOST and DEVICE both come from the SPECIFIED.
167
168
169
170
171
This is what users want on a modern Unix or Windows operating system,
unlike the MERGE-PATHNAME behavior.
Also, if either argument is NIL, then the other argument is returned unmodified;
this is unlike MERGE-PATHNAME which always merges with a pathname,
by default *DEFAULT-PATHNAME-DEFAULTS*, which cannot be NIL."
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
  (when (null specified) (return-from merge-pathnames* defaults))
  (when (null defaults) (return-from merge-pathnames* specified))
  #+scl
  (ext:resolve-pathname specified defaults)
  #-scl
  (let* ((specified (pathname specified))
         (defaults (pathname defaults))
         (directory (normalize-pathname-directory-component (pathname-directory specified)))
         (name (or (pathname-name specified) (pathname-name defaults)))
         (type (or (pathname-type specified) (pathname-type defaults)))
         (version (or (pathname-version specified) (pathname-version defaults))))
    (labels ((unspecific-handler (p)
               (if (typep p 'logical-pathname) #'make-pathname-component-logical #'identity)))
      (multiple-value-bind (host device directory unspecific-handler)
          (ecase (first directory)
            ((:absolute)
             (values (pathname-host specified)
                     (pathname-device specified)
                     directory
                     (unspecific-handler specified)))
            ((nil :relative)
             (values (pathname-host defaults)
                     (pathname-device defaults)
                     (merge-pathname-directory-components directory (pathname-directory defaults))
                     (unspecific-handler defaults))))
        (make-pathname* :host host :device device :directory directory
                        :name (funcall unspecific-handler name)
                        :type (funcall unspecific-handler type)
                        :version (funcall unspecific-handler version))))))

202
203
;;; Some pathname predicates

204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
(defun* pathname-equal (p1 p2)
  (when (stringp p1) (setf p1 (pathname p1)))
  (when (stringp p2) (setf p2 (pathname p2)))
  (flet ((normalize-component (x)
           (and (not (member x '(nil :unspecific :newest (:relative)) :test 'equal)) x)))
    (macrolet ((=? (&rest accessors)
                 (flet ((frob (x)
                          (reduce 'list (cons 'normalize-component accessors)
                                  :initial-value x :from-end t)))
                   `(equal ,(frob 'p1) ,(frob 'p2)))))
      (or (and (null p1) (null 2))
          (and (pathnamep p1) (pathnamep p2)
               (or (equal p1 p2)
                   (=? pathname-host)
                   (=? pathname-device)
                   (=? normalize-pathname-directory-component pathname-directory)
                   (=? pathname-name)
                   (=? pathname-type)
                   (=? pathname-version)))))))


225
226
227
228
229
230
231
232
233
234
235
(defun* absolute-pathname-p (pathspec)
  "If PATHSPEC is a pathname or namestring object that parses as a pathname
possessing an :ABSOLUTE directory component, return the (parsed) pathname.
Otherwise return NIL"
  (and pathspec
       (typep pathspec '(or null pathname string))
       (let ((pathname (pathname pathspec)))
         (and (eq :absolute (car (normalize-pathname-directory-component
                                  (pathname-directory pathname))))
              pathname))))

236
237
238
239
240
241
242
243
244
245
246
247
(defun* relative-pathname-p (pathspec)
  "If PATHSPEC is a pathname or namestring object that parses as a pathname
possessing a :RELATIVE or NIL directory component, return the (parsed) pathname.
Otherwise return NIL"
  (and pathspec
       (typep pathspec '(or null pathname string))
       (let* ((pathname (pathname pathspec))
              (directory (normalize-pathname-directory-component
                          (pathname-directory pathname))))
         (when (or (null directory) (eq :relative (car directory)))
           pathname))))

248
(defun* hidden-pathname-p (pathname)
249
250
  "Return a boolean that is true if the pathname is hidden as per Unix style,
i.e. its name starts with a dot."
251
252
  (and pathname (equal (first-char (pathname-name pathname)) #\.)))

253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287

;;; Directories
(defun* pathname-directory-pathname (pathname)
  "Returns a new pathname with same HOST, DEVICE, DIRECTORY as PATHNAME,
and NIL NAME, TYPE and VERSION components"
  (when pathname
    (make-pathname :name nil :type nil :version nil :defaults pathname)))

(defun* pathname-parent-directory-pathname (pathname)
  "Returns a new pathname with same HOST, DEVICE, DIRECTORY as PATHNAME,
and NIL NAME, TYPE and VERSION components"
  (when pathname
    (make-pathname* :name nil :type nil :version nil
                    :directory (merge-pathname-directory-components
                                '(:relative :back) (pathname-directory pathname))
                    :defaults pathname)))

(defun* directory-pathname-p (pathname)
  "Does PATHNAME represent a directory?

A directory-pathname is a pathname _without_ a filename. The three
ways that the filename components can be missing are for it to be NIL,
:UNSPECIFIC or the empty string.

Note that this does _not_ check to see that PATHNAME points to an
actually-existing directory."
  (when pathname
    (let ((pathname (pathname pathname)))
      (flet ((check-one (x)
               (member x '(nil :unspecific "") :test 'equal)))
        (and (not (wild-pathname-p pathname))
             (check-one (pathname-name pathname))
             (check-one (pathname-type pathname))
             t)))))

288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
(defun* file-pathname-p (pathname)
  "Does PATHNAME represent a file, i.e. has a non-null NAME component?

Accepts NIL, a string (converted through PARSE-NAMESTRING) or a PATHNAME.

Note that this does _not_ check to see that PATHNAME points to an
actually-existing file.

Returns the (parsed) PATHNAME when true"
  (when pathname
    (let* ((pathname (pathname pathname))
           (name (pathname-name pathname)))
      (when (not (member name '(nil :unspecific "") :test 'equal))
        pathname))))

303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
(defun* ensure-directory-pathname (pathspec)
  "Converts the non-wild pathname designator PATHSPEC to directory form."
  (cond
   ((stringp pathspec)
    (ensure-directory-pathname (pathname pathspec)))
   ((not (pathnamep pathspec))
    (error (compatfmt "~@<Invalid pathname designator ~S~@:>") pathspec))
   ((wild-pathname-p pathspec)
    (error (compatfmt "~@<Can't reliably convert wild pathname ~3i~_~S~@:>") pathspec))
   ((directory-pathname-p pathspec)
    pathspec)
   (t
    (make-pathname* :directory (append (or (normalize-pathname-directory-component
                                            (pathname-directory pathspec))
                                           (list :relative))
                                       (list (file-namestring pathspec)))
                    :name nil :type nil :version nil :defaults pathspec))))


;;; Wildcard pathnames
(defparameter *wild* (or #+cormanlisp "*" :wild))
Francois-Rene Rideau's avatar
Francois-Rene Rideau committed
324
325
(defparameter *wild-directory-component* (or #+gcl<2.7 "*" :wild))
(defparameter *wild-inferiors-component* (or #+gcl<2.7 "**" :wild-inferiors))
326
327
(defparameter *wild-file*
  (make-pathname :directory nil :name *wild* :type *wild*
328
                 :version (or #-(or allegro abcl xcl) *wild*)))
329
(defparameter *wild-directory*
Francois-Rene Rideau's avatar
Francois-Rene Rideau committed
330
  (make-pathname* :directory `(:relative ,*wild-directory-component*)
331
332
                  :name nil :type nil :version nil))
(defparameter *wild-inferiors*
Francois-Rene Rideau's avatar
Francois-Rene Rideau committed
333
  (make-pathname* :directory `(:relative ,*wild-inferiors-component*)
334
335
                  :name nil :type nil :version nil))
(defparameter *wild-path*
Francois-Rene Rideau's avatar
Francois-Rene Rideau committed
336
  (merge-pathnames* *wild-file* *wild-inferiors*))
337
338
339
340
341
342

(defun* wilden (path)
  (merge-pathnames* *wild-path* path))


;;; Probing the filesystem
343
(defun* nil-pathname (&optional (defaults *default-pathname-defaults*))
344
345
346
347
348
349
350
351
  ;; 19.2.2.2.1 says a NIL host can mean a default host;
  ;; see also "valid physical pathname host" in the CLHS glossary, that suggests
  ;; strings and lists of strings or :unspecific
  ;; But CMUCL decides to die on NIL.
  (make-pathname* :directory nil :name nil :type nil :version nil :device nil
                  :host (or #+cmu lisp::*unix-host*)
                  ;; the default shouldn't matter, but we really want something physical
                  :defaults defaults))
352
353

(defmacro with-pathname-defaults ((&optional defaults) &body body)
354
  `(let ((*default-pathname-defaults* ,(or defaults '(nil-pathname)))) ,@body))
355

356
(defun* truename* (p)
357
358
359
  ;; avoids both logical-pathname merging and physical resolution issues
  (ignore-errors (with-pathname-defaults () (truename p))))

360
361
362
(defun* probe-file* (p)
  "when given a pathname P, probes the filesystem for a file or directory
with given pathname and if it exists return its truename."
363
364
365
366
367
368
369
  (with-pathname-defaults () ;; avoids logical-pathname issues on some implementations
    (etypecase p
      (null nil)
      (string (probe-file* (parse-namestring p)))
      (pathname (unless (wild-pathname-p p)
                  #.(or #+(or allegro clozure cmu cormanlisp ecl lispworks mkcl sbcl scl)
                        '(probe-file p)
370
371
                        #+clisp (if-bind (it (find-symbol* '#:probe-pathname :ext nil))
                                   `(ignore-errors (,it p)))
372
373
374
375
376
377
378
                        #+gcl<2.7
                        '(or (probe-file p)
                          (and (directory-pathname-p p)
                           (ignore-errors
                            (ensure-directory-pathname
                             (truename* (subpathname (ensure-directory-pathname p) "."))))))
                        '(truename* p)))))))
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396

(defun* safe-file-write-date (pathname)
  ;; If FILE-WRITE-DATE returns NIL, it's possible that
  ;; the user or some other agent has deleted an input file.
  ;; Also, generated files will not exist at the time planning is done
  ;; and calls compute-action-stamp which calls safe-file-write-date.
  ;; So it is very possible that we can't get a valid file-write-date,
  ;; and we can survive and we will continue the planning
  ;; as if the file were very old.
  ;; (or should we treat the case in a different, special way?)
  (and pathname (probe-file* pathname) (ignore-errors (file-write-date pathname))))

(defun* directory* (pathname-spec &rest keys &key &allow-other-keys)
  (apply 'directory pathname-spec
         (append keys '#.(or #+allegro '(:directories-are-files nil :follow-symbolic-links nil)
                             #+clozure '(:follow-links nil)
                             #+clisp '(:circle t :if-does-not-exist :ignore)
                             #+(or cmu scl) '(:follow-links nil :truenamep nil)
397
                             #+sbcl (when (find-symbol* :resolve-symlinks '#:sb-impl nil)
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
                                      '(:resolve-symlinks nil))))))

(defun* filter-logical-directory-results (directory entries merger)
  (if (typep directory 'logical-pathname)
      ;; Try hard to not resolve logical-pathname into physical pathnames;
      ;; otherwise logical-pathname users/lovers will be disappointed.
      ;; If directory* could use some implementation-dependent magic,
      ;; we will have logical pathnames already; otherwise,
      ;; we only keep pathnames for which specifying the name and
      ;; translating the LPN commute.
      (loop :for f :in entries
        :for p = (or (and (typep f 'logical-pathname) f)
                     (let* ((u (ignore-errors (funcall merger f))))
                       ;; The first u avoids a cumbersome (truename u) error.
                       ;; At this point f should already be a truename,
413
414
                       ;; but isn't quite in CLISP, for it doesn't have :version :newest
                       (and u (equal (truename* u) (truename* f)) u)))
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
        :when p :collect p)
      entries))

(defun* directory-files (directory &optional (pattern *wild-file*))
  (let ((dir (pathname directory)))
    (when (typep dir 'logical-pathname)
      ;; Because of the filtering we do below,
      ;; logical pathnames have restrictions on wild patterns.
      ;; Not that the results are very portable when you use these patterns on physical pathnames.
      (when (wild-pathname-p dir)
        (error "Invalid wild pattern in logical directory ~S" directory))
      (unless (member (pathname-directory pattern) '(() (:relative)) :test 'equal)
        (error "Invalid file pattern ~S for logical directory ~S" pattern directory))
      (setf pattern (make-pathname-logical pattern (pathname-host dir))))
    (let ((entries (ignore-errors (directory* (merge-pathnames* pattern dir)))))
      (filter-logical-directory-results
       directory entries
       #'(lambda (f)
           (make-pathname :defaults dir
                          :name (make-pathname-component-logical (pathname-name f))
                          :type (make-pathname-component-logical (pathname-type f))
                          :version (make-pathname-component-logical (pathname-version f))))))))

(defun* subdirectories (directory)
  (let* ((directory (ensure-directory-pathname directory))
         #-(or abcl cormanlisp genera xcl)
         (wild (merge-pathnames*
                #-(or abcl allegro cmu lispworks sbcl scl xcl)
                *wild-directory*
                #+(or abcl allegro cmu lispworks sbcl scl xcl) "*.*"
                directory))
         (dirs
          #-(or abcl cormanlisp genera xcl)
          (ignore-errors
            (directory* wild . #.(or #+clozure '(:directories t :files nil)
                                     #+mcl '(:directories t))))
          #+(or abcl xcl) (system:list-directory directory)
          #+cormanlisp (cl::directory-subdirs directory)
          #+genera (fs:directory-list directory))
         #+(or abcl allegro cmu genera lispworks sbcl scl xcl)
         (dirs (loop :for x :in dirs
                 :for d = #+(or abcl xcl) (extensions:probe-directory x)
                          #+allegro (excl:probe-directory x)
                          #+(or cmu sbcl scl) (directory-pathname-p x)
                          #+genera (getf (cdr x) :directory)
                          #+lispworks (lw:file-directory-p x)
                 :when d :collect #+(or abcl allegro xcl) d
                                  #+genera (ensure-directory-pathname (first x))
                                  #+(or cmu lispworks sbcl scl) x)))
    (filter-logical-directory-results
     directory dirs
     (let ((prefix (or (normalize-pathname-directory-component (pathname-directory directory))
                       '(:absolute)))) ; because allegro returns NIL for #p"FOO:"
       #'(lambda (d)
           (let ((dir (normalize-pathname-directory-component (pathname-directory d))))
             (and (consp dir) (consp (cdr dir))
                  (make-pathname
                   :defaults directory :name nil :type nil :version nil
                   :directory (append prefix (make-pathname-component-logical (last dir)))))))))))

(defun* collect-sub*directories (directory collectp recursep collector)
  (when (funcall collectp directory)
    (funcall collector directory))
  (dolist (subdir (subdirectories directory))
    (when (funcall recursep subdir)
      (collect-sub*directories subdir collectp recursep collector))))


;;; Parsing filenames and lists thereof
484
(defun* split-unix-namestring-directory-components
485
486
    (unix-namestring &key ensure-directory dot-dot)
  "Splits the path string UNIX-NAMESTRING, returning four values:
487
488
A flag that is either :absolute or :relative, indicating
   how the rest of the values are to be interpreted.
489
A directory path --- a list of strings and keywords, suitable for
490
491
492
493
494
495
496
   use with MAKE-PATHNAME when prepended with the flag value.
   Directory components with an empty name or the name . are removed.
   Any directory named .. is read as DOT-DOT, or :BACK if it's NIL (not :UP).
A last-component, either a file-namestring including type extension,
   or NIL in the case of a directory pathname.
A flag that is true iff the unix-style-pathname was just
   a file-namestring without / path specification.
497
ENSURE-DIRECTORY forces the namestring to be interpreted as a directory pathname:
498
499
500
501
502
503
504
the third return value will be NIL, and final component of the namestring
will be treated as part of the directory path.

An empty string is thus read as meaning a pathname object with all fields nil.

Note that : characters will NOT be interpreted as host specification.
Absolute pathnames are only appropriate on Unix-style systems.
505
506

The intention of this function is to support structured component names,
507
e.g., \(:file \"foo/bar\"\), which will be unpacked to relative pathnames."
508
  (check-type unix-namestring string)
509
  (check-type dot-dot (member nil :back :up))
510
511
512
513
  (if (and (not (find #\/ unix-namestring)) (not ensure-directory)
           (plusp (length unix-namestring)))
      (values :relative () unix-namestring t)
      (let* ((components (split-string unix-namestring :separator "/"))
514
515
516
             (last-comp (car (last components))))
        (multiple-value-bind (relative components)
            (if (equal (first components) "")
517
                (if (equal (first-char unix-namestring) #\/)
518
519
520
521
522
523
524
525
526
                    (values :absolute (cdr components))
                    (values :relative nil))
                (values :relative components))
          (setf components (remove-if #'(lambda (x) (member x '("" ".") :test #'equal))
                                      components))
          (setf components (substitute (or dot-dot :back) ".." components :test #'equal))
          (cond
            ((equal last-comp "")
             (values relative components nil nil)) ; "" already removed from components
527
            (ensure-directory
528
529
530
             (values relative components nil nil))
            (t
             (values relative (butlast components) last-comp nil)))))))
531
532

(defun* split-name-type (filename)
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
  "Split a filename into two values NAME and TYPE that are returned.
We assume filename has no directory component.
The last . if any separates name and type from from type,
except that if there is only one . and it is in first position,
the whole filename is the NAME with an empty type.
NAME is always a string.
For an empty type, *UNSPECIFIC-PATHNAME-TYPE* is returned."
  (check-type filename string)
  (assert (plusp (length filename)))
  (destructuring-bind (name &optional (type *unspecific-pathname-type*))
      (split-string filename :max 2 :separator ".")
    (if (equal name "")
        (values filename *unspecific-pathname-type*)
        (values name type))))

548
(defun* parse-unix-namestring (name &rest keys &key type defaults dot-dot ensure-directory
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
                                    &allow-other-keys)
  "Coerce NAME into a PATHNAME using standard Unix syntax.

Unix syntax is used whether or not the underlying system is Unix;
on such non-Unix systems it is only usable but for relative pathnames;
but especially to manipulate relative pathnames portably, it is of crucial
to possess a portable pathname syntax independent of the underlying OS.
This is what PARSE-UNIX-NAMESTRING provides, and why we use it in ASDF.

When given a PATHNAME object, just return it untouched.
When given NIL, just return NIL.
When given a non-null SYMBOL, first downcase its name and treat it as a string.
When given a STRING, portably decompose it into a pathname as below.

#\\/ separates directory components.

The last #\\/-separated substring is interpreted as follows:
566
567
568
569
570
571
1- If TYPE is :DIRECTORY or ENSURE-DIRECTORY is true,
 the string is made the last directory component, and NAME and TYPE are NIL.
 if the string is empty, it's the empty pathname with all slots NIL.
2- If TYPE is NIL, the substring is file-namestring, and its NAME and TYPE
 are separated by SPLIT-NAME-TYPE.
3- If TYPE is a string, it is the given TYPE, and the whole string is the NAME.
572
573

Directory components with an empty name the name . are removed.
574
575
Any directory named .. is read as DOT-DOT,
which must be one of :BACK or :UP and defaults to :BACK.
576
577

HOST, DEVICE and VERSION components are taken from DEFAULTS,
578
which itself defaults to (ROOT-PATHNAME), also used if DEFAULTS in NIL.
579
No host or device can be specified in the string itself,
580
which makes it unsuitable for absolute pathnames outside Unix.
581

582
583
584
For relative pathnames, these components (and hence the defaults) won't matter
if you use MERGE-PATHNAMES* but will matter if you use MERGE-PATHNAMES,
which is an important reason to always use MERGE-PATHNAMES*.
585

586
587
588
589
590
Arbitrary keys are accepted, and the parse result is passed to ENSURE-PATHNAME
with those keys, removing TYPE DEFAULTS and DOT-DOT.
When you're manipulating pathnames that are supposed to make sense portably
even though the OS may not be Unixish, we recommend you use :WANT-RELATIVE T
to throw an error if the pathname is absolute"
591
592
  (block nil
    (check-type type (or null string (eql :directory)))
593
594
    (when (eq type :directory)
      (setf ensure-directory t))
595
596
597
598
599
600
    (etypecase name
      ((or null pathname) (return name))
      (symbol
       (setf name (string-downcase name)))
      (string))
    (multiple-value-bind (relative path filename file-only)
601
        (split-unix-namestring-directory-components
602
         name :dot-dot dot-dot :ensure-directory ensure-directory)
603
604
      (multiple-value-bind (name type)
          (cond
605
            ((or ensure-directory (null filename))
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
             (values nil nil))
            (type
             (values filename type))
            (t
             (split-name-type filename)))
        (apply 'ensure-pathname
               (make-pathname*
                :directory (unless file-only (cons relative path))
                :name name :type type
                :defaults (or defaults (nil-pathname)))
               (remove-keys '(:type :dot-dot :defaults) keys))))))

(defun* unix-namestring (pathname)
  "Given a non-wild PATHNAME, return a Unix-style namestring for it.
If the PATHNAME is NIL or a STRING, return it unchanged.

This only considers the DIRECTORY, NAME and TYPE components of the pathname.
This is a portable solution for representing relative pathnames,
But unless you are running on a Unix system, it is not a general solution
to representing native pathnames.

An error is signaled if the argument is not NULL, a STRING or a PATHNAME,
or if it is a PATHNAME but some of its components are not recognized."
  (etypecase pathname
    ((or null string) pathname)
    (pathname
     (with-output-to-string (s)
       (flet ((err () (error "Not a valid unix-namestring ~S" pathname)))
         (let* ((dir (normalize-pathname-directory-component (pathname-directory pathname)))
                (name (pathname-name pathname))
                (type (pathname-type pathname))
                (type (and (not (eq type :unspecific)) type)))
638
           (cond
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
             ((eq dir ()))
             ((eq dir '(:relative)) (princ "./" s))
             ((consp dir)
              (destructuring-bind (relabs &rest dirs) dir
                (or (member relabs '(:relative :absolute)) (err))
                (when (eq relabs :absolute) (princ #\/ s))
                (loop :for x :in dirs :do
                  (cond
                    ((member x '(:back :up)) (princ "../" s))
                    ((equal x "") (err))
                    ;;((member x '("." "..") :test 'equal) (err))
                    ((stringp x) (format s "~A/" x))
                    (t (err))))))
             (t (err)))
           (cond
             (name
              (or (and (stringp name) (or (null type) (stringp type))) (err))
              (format s "~A~@[.~A~]" name type))
657
             (t
658
              (or (null type) (err))))))))))
659
660

(defun* subpathname (pathname subpath &key type)
661
662
663
664
665
666
667
668
669
  "This function takes a PATHNAME and a SUBPATH and a TYPE.
If SUBPATH is already a PATHNAME object (not namestring),
and is an absolute pathname at that, it is returned unchanged;
otherwise, SUBPATH is turned into a relative pathname with given TYPE
as per PARSE-UNIX-NAMESTRING with :WANT-RELATIVE T :TYPE TYPE,
then it is merged with the PATHNAME-DIRECTORY-PATHNAME of PATHNAME."
  (or (and (pathnamep subpath) (absolute-pathname-p subpath))
      (merge-pathnames* (parse-unix-namestring subpath :type type :want-relative t)
                        (pathname-directory-pathname pathname))))
670
671

(defun* subpathname* (pathname subpath &key type)
672
  "returns NIL if the base pathname is NIL, otherwise like SUBPATHNAME."
673
674
675
676
677
678
679
680
681
682
683
  (and pathname
       (subpathname (ensure-directory-pathname pathname) subpath :type type)))

;;; Pathname host and its root
(defun* pathname-root (pathname)
  (make-pathname* :directory '(:absolute)
                  :name nil :type nil :version nil
                  :defaults pathname ;; host device, and on scl, *some*
                  ;; scheme-specific parts: port username password, not others:
                  . #.(or #+scl '(:parameters nil :query nil :fragment nil))))

684
(defun* pathname-host-pathname (pathname)
685
686
687
  (make-pathname* :directory nil
                  :name nil :type nil :version nil :device nil
                  :defaults pathname ;; host device, and on scl, *some*
688
689
690
                  ;; scheme-specific parts: port username password, not others:
                  . #.(or #+scl '(:parameters nil :query nil :fragment nil))))

691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
#-scl
(defun* directory-separator-for-host (&optional (pathname *default-pathname-defaults*))
  (let ((foo (make-pathname* :directory '(:absolute "FOO") :defaults pathname)))
    (last-char (namestring foo))))

#-scl
(defun* directorize-pathname-host-device (pathname)
  (let* ((root (pathname-root pathname))
         (wild-root (wilden root))
         (absolute-pathname (merge-pathnames* pathname root))
         (separator (directory-separator-for-host root))
         (root-namestring (namestring root))
         (root-string
          (substitute-if #\/
                         #'(lambda (x) (or (eql x #\:)
                                           (eql x separator)))
                         root-namestring)))
    (multiple-value-bind (relative path filename)
709
        (split-unix-namestring-directory-components root-string :ensure-directory t)
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
      (declare (ignore relative filename))
      (let ((new-base
             (make-pathname* :defaults root :directory `(:absolute ,@path))))
        (translate-pathname absolute-pathname wild-root (wilden new-base))))))

#+scl
(defun* directorize-pathname-host-device (pathname)
  (let ((scheme (ext:pathname-scheme pathname))
        (host (pathname-host pathname))
        (port (ext:pathname-port pathname))
        (directory (pathname-directory pathname)))
    (flet ((specificp (x) (and x (not (eq x :unspecific)))))
      (if (or (specificp port)
              (and (specificp host) (plusp (length host)))
              (specificp scheme))
        (let ((prefix ""))
          (when (specificp port)
            (setf prefix (format nil ":~D" port)))
          (when (and (specificp host) (plusp (length host)))
            (setf prefix (strcat host prefix)))
          (setf prefix (strcat ":" prefix))
          (when (specificp scheme)
            (setf prefix (strcat scheme prefix)))
          (assert (and directory (eq (first directory) :absolute)))
          (make-pathname* :directory `(:absolute ,prefix ,@(rest directory))
                          :defaults pathname)))
    pathname)))


;;; Resolving symlinks somewhat
(defun* truenamize (pathname &optional (defaults *default-pathname-defaults*))
  "Resolve as much of a pathname as possible"
  (block nil
    (when (typep pathname '(or null logical-pathname)) (return pathname))
    (let ((p (merge-pathnames* pathname defaults)))
      (when (typep p 'logical-pathname) (return p))
      (let ((found (probe-file* p)))
        (when found (return found)))
      (unless (absolute-pathname-p p)
749
        (let ((true-defaults (truename* defaults)))
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
          (when true-defaults
            (setf p (merge-pathnames pathname true-defaults)))))
      (unless (absolute-pathname-p p) (return p))
      (let ((sofar (probe-file* (pathname-root p))))
        (unless sofar (return p))
        (flet ((solution (directories)
                 (merge-pathnames*
                  (make-pathname* :host nil :device nil
                                  :directory `(:relative ,@directories)
                                  :name (pathname-name p)
                                  :type (pathname-type p)
                                  :version (pathname-version p))
                  sofar)))
          (loop :with directory = (normalize-pathname-directory-component
                                   (pathname-directory p))
            :for component :in (cdr directory)
            :for rest :on (cdr directory)
            :for more = (probe-file*
                         (merge-pathnames*
                          (make-pathname* :directory `(:relative ,component))
                          sofar)) :do
            (if more
                (setf sofar more)
                (return (solution rest)))
            :finally
            (return (solution nil))))))))

(defun* resolve-symlinks (path)
  #-allegro (truenamize path)
779
780
  #+allegro
  (if (physical-pathname-p path)
781
      (or (ignore-errors (excl:pathname-resolve-symbolic-links path)) path)
782
      path))
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849

(defun* resolve-symlinks* (path)
  (if *resolve-symlinks*
      (and path (resolve-symlinks path))
      path))


;;; absolute vs relative
(defun* ensure-pathname-absolute (path)
  (cond
    ((absolute-pathname-p path) path)
    ((stringp path) (ensure-pathname-absolute (pathname path)))
    ((not (pathnamep path)) (error "not a valid pathname designator ~S" path))
    (t (let ((resolved (resolve-symlinks path)))
         (assert (absolute-pathname-p resolved))
         resolved))))

(defun* relativize-directory-component (directory-component)
  (let ((directory (normalize-pathname-directory-component directory-component)))
    (cond
      ((stringp directory)
       (list :relative directory))
      ((eq (car directory) :absolute)
       (cons :relative (cdr directory)))
      (t
       directory))))

(defun* relativize-pathname-directory (pathspec)
  (let ((p (pathname pathspec)))
    (make-pathname*
     :directory (relativize-directory-component (pathname-directory p))
     :defaults p)))


;;; Simple filesystem operations
(defun* ensure-all-directories-exist (pathnames)
   (dolist (pathname pathnames)
     (ensure-directories-exist (translate-logical-pathname pathname))))

(defun* rename-file-overwriting-target (source target)
  #+clisp ;; But for a bug in CLISP 2.48, we should use :if-exists :overwrite and be atomic
  (posix:copy-file source target :method :rename)
  #-clisp
  (rename-file source target
               #+clozure :if-exists #+clozure :rename-and-delete))

(defun* delete-file-if-exists (x)
  (when (and x (probe-file* x))
    (delete-file x)))

;;; Translate a pathname
(defun* translate-pathname* (path absolute-source destination &optional root source)
  (declare (ignore source))
  (cond
    ((functionp destination)
     (funcall destination path absolute-source))
    ((eq destination t)
     path)
    ((not (pathnamep destination))
     (error "Invalid destination"))
    ((not (absolute-pathname-p destination))
     (translate-pathname path absolute-source (merge-pathnames* destination root)))
    (root
     (translate-pathname (directorize-pathname-host-device path) absolute-source destination))
    (t
     (translate-pathname path absolute-source destination))))

850

851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
;;; Temporary pathnames
(defun* add-pathname-suffix (pathname suffix)
  (make-pathname :name (strcat (pathname-name pathname) suffix)
                 :defaults pathname))

(defun* tmpize-pathname (x)
  (add-pathname-suffix x "-ASDF-TMP"))

(defun* call-with-staging-pathname (pathname fun)
  "Calls fun with a staging pathname, and atomically
renames the staging pathname to the pathname in the end.
Note: this protects only against failure of the program,
not against concurrent attempts.
For the latter case, we ought pick random suffix and atomically open it."
  (let* ((pathname (pathname pathname))
         (staging (tmpize-pathname pathname)))
    (unwind-protect
         (multiple-value-prog1
             (funcall fun staging)
           (rename-file-overwriting-target staging pathname))
      (when (probe-file* staging)
        (delete-file staging)))))

(defmacro with-staging-pathname ((pathname-var &optional (pathname-value pathname-var)) &body body)
  `(call-with-staging-pathname ,pathname-value #'(lambda (,pathname-var) ,@body)))

;;; Basic pathnames
878
879
880
(defun* logical-pathname-p (x)
  (typep x 'logical-pathname))

881
(defun* physical-pathname-p (x)
882
  (and (pathnamep x) (not (logical-pathname-p x))))
883

884
(defun* sane-physical-pathname (&key defaults (keep t) fallback want-existing)
885
886
887
888
889
890
891
892
893
894
  (flet ((sanitize (x)
           (setf x (and x (ignore-errors (translate-logical-pathname x))))
           (when (pathnamep x)
             (setf x
                   (ecase keep
                     ((t) x)
                     ((:directory) (pathname-directory-pathname x))
                     ((:root) (pathname-root x))
                     ((:host) (pathname-host-pathname x))
                     ((nil) (nil-pathname x))))
895
             (when want-existing ;; CCL's probe-file will choke if d-p-d is logical
896
897
898
               (setf x (and (probe-file* x) x)))
             (and (physical-pathname-p x) x))))
    (or (sanitize defaults)
899
        (when fallback
900
901
902
903
          (or (sanitize (nil-pathname))
              (sanitize (ignore-errors (user-homedir-pathname)))))
        (error "Could not find a sane a physical pathname~
                ~@[ from ~S~]~@[~:*~@[ or~*~] fallbacks~]"
904
905
               defaults fallback))))

906
907
908
909
910
(defun* root-pathname ()
  "On a Unix system, this will presumably be the root pathname /.
Otherwise, this will be the root of some implementation-dependent filesystem host."
  (sane-physical-pathname :keep :root :fallback t))

911

912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
;;;; -----------------------------------------------------------------
;;;; Windows shortcut support.  Based on:
;;;;
;;;; Jesse Hager: The Windows Shortcut File Format.
;;;; http://www.wotsit.org/list.asp?fc=13

#-(or clisp genera) ; CLISP doesn't need it, and READ-SEQUENCE annoys old Genera.
(progn
(defparameter *link-initial-dword* 76)
(defparameter *link-guid* #(1 20 2 0 0 0 0 0 192 0 0 0 0 0 0 70))

(defun* read-null-terminated-string (s)
  (with-output-to-string (out)
    (loop :for code = (read-byte s)
      :until (zerop code)
      :do (write-char (code-char code) out))))

(defun* read-little-endian (s &optional (bytes 4))
  (loop :for i :from 0 :below bytes
    :sum (ash (read-byte s) (* 8 i))))

(defun* parse-file-location-info (s)
  (let ((start (file-position s))
        (total-length (read-little-endian s))
        (end-of-header (read-little-endian s))
        (fli-flags (read-little-endian s))
        (local-volume-offset (read-little-endian s))
        (local-offset (read-little-endian s))
        (network-volume-offset (read-little-endian s))
        (remaining-offset (read-little-endian s)))
    (declare (ignore total-length end-of-header local-volume-offset))
    (unless (zerop fli-flags)
      (cond
        ((logbitp 0 fli-flags)
          (file-position s (+ start local-offset)))
        ((logbitp 1 fli-flags)
          (file-position s (+ start
                              network-volume-offset
                              #x14))))
      (strcat (read-null-terminated-string s)
              (progn
                (file-position s (+ start remaining-offset))
                (read-null-terminated-string s))))))

(defun* parse-windows-shortcut (pathname)
  (with-open-file (s pathname :element-type '(unsigned-byte 8))
    (handler-case
        (when (and (= (read-little-endian s) *link-initial-dword*)
                   (let ((header (make-array (length *link-guid*))))
                     (read-sequence header s)
                     (equalp header *link-guid*)))
          (let ((flags (read-little-endian s)))
            (file-position s 76)        ;skip rest of header
            (when (logbitp 0 flags)
              ;; skip shell item id list
              (let ((length (read-little-endian s 2)))
                (file-position s (+ length (file-position s)))))
            (cond
              ((logbitp 1 flags)
                (parse-file-location-info s))
              (t
                (when (logbitp 2 flags)
                  ;; skip description string
                  (let ((length (read-little-endian s 2)))
                    (file-position s (+ length (file-position s)))))
                (when (logbitp 3 flags)
                  ;; finally, our pathname
                  (let* ((length (read-little-endian s 2))
                         (buffer (make-array length)))
                    (read-sequence buffer s)
                    (map 'string #'code-char buffer)))))))
      (end-of-file (c)
        (declare (ignore c))
        nil)))))
986

987
988
989
990

;;; Check pathname constraints

(defun* ensure-pathname
991
992
993
994
    (pathname &key
              error-arguments
              defaults type dot-dot
              want-pathname
995
              want-logical want-physical ensure-physical
996
997
998
999
1000
1001
1002
1003
1004
              want-relative want-absolute ensure-absolute ensure-subpath
              want-non-wild want-wild wilden
              want-file want-directory ensure-directory
              want-existing ensure-directories-exist
              ensure-truename truenamize
              &aux (p pathname)) ;; mutable working copy, preserve original
  "Coerces its argument into a PATHNAME,
optionally doing some transformations and checking specified constraints.

1005
If the argument is NIL, then NIL is returned unless the WANT-PATHNAME constraint is specified.
1006
1007
1008
1009
1010
1011

If the argument is a STRING, it is first converted to a pathname via PARSE-UNIX-NAMESTRING
reusing the keywords DEFAULTS TYPE DOT-DOT ENSURE-DIRECTORY WANT-RELATIVE;
then the result is optionally merged into the DEFAULTS if ENSURE-ABSOLUTE is true,
and the all the checks and transformations are run.

1012
1013
1014
1015
1016
Each non-nil constraint argument can be one of the symbols T, ERROR, CERROR or IGNORE.
The boolean T is an alias for ERROR.
ERROR means that an error will be raised if the constraint is not satisfied.
CERROR means that an continuable error will be raised if the constraint is not satisfied.
IGNORE means just return NIL instead of the pathname.
1017

1018
1019
The ERROR-ARGUMENTS arguments, if provided,
will be passed on to the error primitive, together with three arguments:
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
the pathname, the keyword :reason, and a list (KEYWORD FORMAT ARGUMENTS)
  the keyword that corresponds to that constraint name
  a format string describing the error
  and a list of any additional arguments required by said format string.
This makes it usable whether you are using the short or long variants of ERROR,
modulo your error object having to recognize the keyword :reason
in case you use the long variant.

The transformations and constraint checks are done in this order,
which is also the order in the lambda-list:

WANT-PATHNAME checks that pathname (after parsing if needed) is not null.
Otherwise, if the pathname is NIL, ensure-pathname returns NIL.
WANT-LOGICAL checks that pathname is a LOGICAL-PATHNAME
WANT-PHYSICAL checks that pathname is not a LOGICAL-PATHNAME
ENSURE-PHYSICAL ensures that pathname is physical via TRANSLATE-LOGICAL-PATHNAME
WANT-RELATIVE checks that pathname has a relative directory component
WANT-ABSOLUTE checks that pathname does have an absolute directory component
ENSURE-ABSOLUTE merges with the DEFAULTS, then checks again
that the result absolute is an absolute pathname indeed.
ENSURE-SUBPATH checks that the pathname is a subpath of the DEFAULTS.
WANT-FILE checks that pathname has a non-nil FILE component
WANT-DIRECTORY checks that pathname has nil FILE and TYPE components
ENSURE-DIRECTORY uses ENSURE-DIRECTORY-PATHNAME to interpret
any file and type components as being actually a last directory component.
WANT-NON-WILD checks that pathname is not a wild pathname
WANT-WILD checks that pathname is a wild pathname
WILDEN merges the pathname with **/*.*.* if it is not wild
WANT-EXISTING checks that a file (or directory) exists with that pathname.
ENSURE-DIRECTORIES-EXIST creates any parent directory with ENSURE-DIRECTORIES-EXIST.
ENSURE-TRUENAME replaces the pathname by its truename, or errors if not possible.
TRUENAMIZE uses TRUENAMIZE to resolve as many symlinks as possible."
1052
  (block nil
1053
1054
1055
    (flet ((report-error (on-error keyword description &rest arguments)
             (let ((err (append (or error-arguments '("Invalid pathname ~S: ~*~{~*~?~}"))
                                (list pathname :reason (list keyword description arguments)))))
1056
1057
1058
1059
               (ecase on-error
                 ((error t) (apply 'error err))
                 ((cerror) (apply 'cerror "ignore pathname constraint" err))
                 ((ignore) (return nil))))))
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
      (macrolet ((err (constraint &rest arguments)
                   `(report-error ,constraint ',(intern* constraint :keyword) ,@arguments))
                 (check (constraint condition &rest arguments)
                   `(when ,constraint
                      (unless ,condition (err ,constraint ,@arguments))))
                 (transform (flag condition expr)
                   `(when ,flag
                      (,@(if condition `(when ,condition) '(progn))
                       (setf p ,expr)))))
        (etypecase p
          ((or null pathname))
1071
          (string
1072
1073
1074
1075
1076
           (setf p (parse-unix-namestring
                    p :defaults defaults :type type :dot-dot dot-dot
                    :ensure-directory ensure-directory :want-relative want-relative))))
        (check want-pathname (pathnamep p) "Expected a pathname, not NIL")
        (unless pathname (return NIL))
1077
        (check want-logical (logical-pathname-p p) "Expected a logical pathname")
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
        (check want-physical (physical-pathname-p p) "Expected a physical pathname")
        (transform ensure-physical () (translate-logical-pathname p))
        (check ensure-physical (physical-pathname-p p) "Could not translate to a physical pathname")
        (check want-relative (relative-pathname-p p) "Expected a relative pathname")
        (check want-absolute (absolute-pathname-p p) "Expected an absolute pathname")
        (transform ensure-absolute (not (absolute-pathname-p p)) (merge-pathnames* defaults p))
        (check ensure-absolute (absolute-pathname-p p)
               "Could not make into an absolute pathname even after merging with ~S" defaults)
        (check ensure-subpath (absolute-pathname-p defaults)
               "cannot be checked to be a subpath of non-absolute pathname ~S" defaults)
        (check ensure-subpath (not (absolute-pathname-p (enough-namestring p defaults)))
               "is not a sub pathname of ~S" defaults)
        (check want-file (file-pathname-p p) "Expected a file pathname")
        (check want-directory (directory-pathname-p p) "Expected a directory pathname")
        (transform ensure-directory (not (directory-pathname-p p)) (ensure-directory-pathname p))
        (check want-non-wild (not (wild-pathname-p p)) "Expected a non-wildcard pathname")
        (check want-wild (wild-pathname-p p) "Expected a wildcard pathname")
        (transform wilden (not (wild-pathname-p p)) (wilden p))
1096
        (when want-existing
1097
          (let ((existing (probe-file* p)))
1098
            (if existing
1099
                (when (or ensure-truename truenamize)
1100
                  (return existing))
1101
1102
1103
1104
                (err want-existing "Expected an existing pathname"))))
        (when ensure-directories-exist (ensure-directories-exist p))
        (when ensure-truename
          (let ((truename (truename* p)))
1105
1106
            (if truename
                (return truename)
1107
1108
1109
                (err truename "Can't get a truename for pathname"))))
        (transform truenamize () (truenamize p))
        p))))
1110
1111


1112
;;; Hook for output translations
1113
(defvar *output-translation-function* 'identity)