;; Inspired from `dired-create-directory` code.
(defun with-temp-dir (dir)
"..."
(let* ((expanded (directory-file-name (expand-file-name dir)))
(try expanded)
new)
(unwind-protect
(progn
(when (file-exists-p expanded)
(error "Cannot create directory %s: file exists" expanded))
;; Find the topmost nonexistent parent dir (variable `new')
(while (and try (not (file-exists-p try)) (not (equal new try)))
(setq new try
try (directory-file-name (file-name-directory try))))
(make-directory expanded t)
(write-test-files expanded)
(other-test-functions expanded))
(delete-directory new t))))
Or if you want to do arbitrary things in the directory, not just write-test-files
and other-test-functions
, use a macro:
(defmacro with-temp-dir (dir &rest body)
"..."
`(let* ((expanded (directory-file-name (expand-file-name ',dir)))
(try expanded)
new)
(unwind-protect
(progn
(when (file-exists-p expanded)
(error "Cannot create directory %s: file exists" expanded))
;; Find the topmost nonexistent parent dir (variable `new')
(while (and try (not (file-exists-p try)) (not (equal new try)))
(setq new try
try (directory-file-name (file-name-directory try))))
(make-directory expanded t)
,@body)
(delete-directory new t))))
Then you would do, e.g.:
(with-temp-dir "/your/temp/dir" (write-test-files ...) (other-test-functions ...))