Skip to content

Commit

Permalink
Add update-file function (#77)
Browse files Browse the repository at this point in the history
  • Loading branch information
PavlosMelissinos committed Nov 12, 2022
1 parent c43b784 commit 4b2afa7
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
10 changes: 10 additions & 0 deletions src/babashka/fs.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -1103,3 +1103,13 @@
(write-lines "/tmp/out.txt" (line-seq (io/reader "/tmp/out.txt")) {:charset "latin1"})
(slurp "/tmp/out.txt")
)

(defn update-file
"Swaps the contents of file to be:
(apply f current-contents-of-file args). f should be free of side effects.
Returns the value that was swapped in."
[file f & xs]
(let [old-val (slurp file)
new-val (apply f old-val xs)]
(spit file new-val)
new-val))
21 changes: 20 additions & 1 deletion test/babashka/fs_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
[clojure.java.io :as io]
[clojure.set :as set]
[clojure.string :as str]
[clojure.test :refer [deftest is testing]]))
[clojure.test :refer [deftest is testing]])
(:import [java.io FileNotFoundException]))

(def windows? (-> (System/getProperty "os.name")
(str/lower-case)
Expand Down Expand Up @@ -575,3 +576,21 @@
(is (= (repeat 3 "foo") (fs/read-all-lines f)))
(fs/write-lines f (repeat 3 "foo") {:append true})
(is (= (repeat 6 "foo") (fs/read-all-lines f)))))

(deftest test-update-file
(let [file (fs/file (fs/temp-dir) (str (gensym)))]
(testing "Throws if file doesn't exist"
(is (thrown? FileNotFoundException (= "foooo" (fs/update-file file str "foooo")))))

(spit file "foo")
(is (= "foobar" (fs/update-file file #(str % "bar"))))
(is (= "foobar" (slurp file)))
(is (= "foobarbazbatcat" (fs/update-file file str "baz" "bat" "cat")))
(is (= "foobarbazbatcat" (slurp file)))

(let [new-val (fs/update-file file str (rand))]
(is (= new-val (slurp file)))))

(let [file (fs/file (fs/temp-dir) (str (gensym)))]
(spit file ", ")
(is (= "foo, bar, baz" (fs/update-file file str/join ["foo" "bar" "baz"])))))

0 comments on commit 4b2afa7

Please sign in to comment.