Commit 79d708ff authored by Magnus Therning's avatar Magnus Therning

[clj] Start

(defproject fcis-refactor "0.1.0-SNAPSHOT"
:description "FCIS refactoring exercise"
:dependencies [[org.clojure/clojure "1.10.1"]
[clj-commons/fs "1.5.2"]
[digest "1.4.9"]])
(ns sync.sync
(:require [me.raynes.fs :as fs]
(defn hash-file [path]
(digest/sha-1 path))
(defn do-sync [src dest]
(let [source-hashes (atom {})
seen (atom #{})]
;; walk the source folder and build a map of filenames and their hashes
(doseq [fil (fs/list-dir src)]
(swap! source-hashes #(assoc % (hash-file fil) (fs/base-name fil))))
;; walk the targe folder and get the filenmaes and hashes
(doseq [fil (fs/list-dir dest)]
(let [the-hash (hash-file fil)]
(swap! seen #(conj % the-hash))
;; if there's a file in target that's not in source, delete it
(not ((set (keys @source-hashes)) the-hash))
(fs/delete fil)
;; if theres a file in target that has a different path in source,
;; move it o the correct path
(and ((set (keys @source-hashes)) the-hash)
(not= (get @source-hashes the-hash) (fs/base-name fil)))
(fs/rename fil (str dest "/" (get @source-hashes the-hash))))))
;; for every file that appears in source but not target, copy the file to
;; the target
(doseq [[the-hash file-name] @source-hashes]
(if (not (@seen the-hash))
(fs/copy (str src "/" file-name ) (str dest "/" file-name))))))
(ns sync.sync-test
(:require [sync.sync :as sut]
[clojure.test :as t]
[me.raynes.fs :as fs]))
(t/deftest do-sync-test
(t/testing "file in src not in dest"
(with-redefs [fs/tmpdir (fn [] "./")]
;; create tmp dirs (src, dest)
(let [srcdir (fs/temp-dir "test0_src-")
destdir (fs/temp-dir "test0_dest-")]
;; put a file in src
(spit (str srcdir "/my-file") "I am a very useful file")
;; -- sync --
(sut/do-sync srcdir destdir)
;; ----------
;; verify
;; - file is in dest
(t/is (fs/file? (str destdir "/my-file")))
;; - file contents
(t/is (= "I am a very useful file" (slurp (str destdir "/my-file"))))
;; remove tmp dirs
(fs/delete-dir srcdir)
(fs/delete-dir destdir))))
(t/testing "file rename in src"
(with-redefs [fs/tmpdir (fn [] "./")]
;; create tmp dirs
(let [srcdir (fs/temp-dir "test1-src-")
destdir (fs/temp-dir "test1-dest-")
file-content "I am a file that was renamed"]
;; put a file in src
(spit (str srcdir "/source-filename") file-content)
;; put a file in dest - with same content but different name
(spit (str destdir "/dest-filename") file-content)
;; -- sync --
(sut/do-sync srcdir destdir)
;; ----------
;; verify
;; - old dest file doesn't exist
(t/is (fs/file? (str destdir "/source-filename")))
;; - new file has correct content
(t/is (= file-content (slurp (str destdir "/source-filename"))))
;; remove the tmp dirs
(fs/delete-dir srcdir)
(fs/delete-dir destdir)))))
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment