aboutsummaryrefslogtreecommitdiff
path: root/scripts/grep-write.clj
blob: e730dae495a56176394d259a2fdf86cf6cfbe464 (plain) (blame)
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
#!/usr/bin/env bb

(require '[clojure.string :as str])

(defn read-file-lines [filepath]
  (-> filepath slurp (str/split #"\r?\n" -1)))

(defn parse-vimgrep [line]
  (when-let [[_ filepath linenr col text] (re-matches #"(.*):(\d+):(\d+):(.*)" line)]
    [filepath (parse-long linenr) col text]))

(defn update-line [filepath linenr text]
  (let [lines (read-file-lines filepath)
        line-changed? #(not= (nth lines (dec linenr)) text)]
    (when (and (> (count lines) linenr) (line-changed?))
      (let [new-lines (assoc lines (dec linenr) text)]
        (spit filepath (str/join "\n" new-lines))
        true))))

(defn apply-vimgrep-change [vimgrep-line]
  (when-let [[filepath linenr _ text] (parse-vimgrep vimgrep-line)]
    (update-line filepath linenr text)))

(defn grep-write []
  (->> (line-seq (java.io.BufferedReader. *in*))
       (keep apply-vimgrep-change)
       count))

(let [change-count (grep-write)]
  (println (str "Applied " change-count " changes")))