Skip to content

Instantly share code, notes, and snippets.

@mccraigmccraig
Created March 10, 2017 15:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mccraigmccraig/07b32fbb27950013c8f52917d2c40da8 to your computer and use it in GitHub Desktop.
Save mccraigmccraig/07b32fbb27950013c8f52917d2c40da8 to your computer and use it in GitHub Desktop.
(ns boot.rewrite
(:require
[clojure.java.io :as io]
[clojure.string :as str]
[boot.util :as util]
[boot.core :as core]))
(defmulti rewrite-transform
"Transform a file at inf, writing to outf"
(fn [transform-key args inf outf]
transform-key))
(defmethod rewrite-transform :string-replace
[_ [pattern replacement] inf outf]
(let [patt (re-pattern pattern)
lines (-> inf io/reader line-seq)]
(util/info (prn-str "string-replace" inf outf pattern replacement))
(io/make-parents outf)
(with-open [out (io/writer outf)]
(->> lines
(reduce
(fn [started? l]
(when (and started? (not-empty l))
(.write out "\n"))
(.write out (str/replace l patt replacement))
true)
false)))))
(defn- rewrite-files
[match v? transform-key args]
(util/info (prn-str "rewrite-transform" match v? transform-key args))
(let [tmp (core/tmp-dir!)]
(fn [fileset]
(core/empty-dir! tmp)
(let [output-files (core/output-files fileset)
mfiles (core/by-re match output-files v?)]
(doseq [mf mfiles]
(let [in-file (core/tmp-file mf)
path (core/tmp-path mf)
out-file (io/file tmp path)]
(rewrite-transform transform-key args in-file out-file))))
(core/add-resource fileset tmp))))
(core/deftask rewrite
"Rewrite files according to a transform
The --match option specifies a list of regexes to select files
to transform from the fileset. The --invert option can be used
to invert the sense of the match.
The --transform option specifies the transform to apply to matched
files. The transform keyword and any positional args are given to the
rewrite-transform multimethod"
[m match MATCH #{regex} "The set of regexes that paths must match."
v invert bool "Invert the sense of matching."
t transform TRANSFORM kw "Keyword identifying the transform"]
(util/info (prn-str "rewrite" *opts* *args*))
(let [process (rewrite-files match invert transform *args*)]
(core/with-pre-wrap [fs]
(->> fs process core/commit!))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment