-
Notifications
You must be signed in to change notification settings - Fork 0
/
find_and_replace.clj
31 lines (27 loc) · 1.02 KB
/
find_and_replace.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
(ns derivative.transformations.content.find-and-replace
(:require
[clojure.string :as string]
[derivative.specs.core :as specs]
[derivative.specs.content :as content-specs]
[derivative.templating.core :as templates]
[derivative.transformations.core :refer [apply-transformation]])
(:import
[java.util.regex Pattern]))
(defn with-match-map [context match]
(assoc context
:match
(into {}
(map-indexed
(fn [index item] [(keyword (str "$" index)) item])
match))))
(defn find-and-replace [{:keys [find replace context]}]
(fn [content]
(let [find-rendered (templates/render (specs/strip-syntax find) context)
find-pattern (re-pattern
(if (content-specs/string-syntax? find)
(Pattern/quote find-rendered)
find-rendered))
replace-fn
#(templates/render (specs/strip-syntax replace)
(with-match-map context %))]
(string/replace content find-pattern replace-fn))))