Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Interest in a with-temp-files macro #256

@NoahTheDuke

Description

@NoahTheDuke

I wrote a with-temp-files macro for Splint that I've found enormously helpful, and when I reached for it again recently in another project, I thought "should this just exist in bb/fs"?

Here it is in full, if there's interest I'll open a PR:

(defmacro with-temp-files
  "Initialize a temp directory with given files, bind the files to the given
  symbols, execute the body with those bound, then delete the directory.
  file-binds are pairs of simple-symbols and strings. The symbols will be
  available in the body, and the strings will be interpreted as file paths
  (with optionally specified parent directories).

  (with-temp-files
    [core \"src/noahtheduke/core.clj\"]
    (spit core \"(ns noahtheduke.core)\"))"
  [file-binds & body]
  (let [paths (take-nth 2 (drop 1 file-binds))
        temp-dir (gensym)
        temp-files (map
                     (fn [path]
                       [(gensym)
                        `(let [f# (fs/file (str ~temp-dir) ~path)]
                           (fs/create-dirs (fs/path (fs/file (fs/parent f#))))
                           (fs/create-file (fs/path f#)))])
                     paths)
        binds (mapcat vector
                (take-nth 2 file-binds)
                (map (fn [[path _]] `(fs/file (str ~path)))
                  temp-files))]
    `(let [~temp-dir (fs/create-temp-dir)
           ~@(apply concat temp-files)
           ~@binds]
       (try (let [res# (do ~@body)] res#)
         (finally
           (fs/walk-file-tree
             ~temp-dir
             {:post-visib-directory (fn [dir# attrs#]
                                      (fs/delete-if-exists dir#)
                                      :continue)
              :visit-file (fn [path# attrs#]
                            (fs/delete-if-exists path#)
                            :continue)}))))))

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions