Skip to content

Commit

Permalink
Move hashing css file step from shadow-cljs hook to build (#3)
Browse files Browse the repository at this point in the history
  • Loading branch information
abogoyavlensky authored Jun 2, 2024
1 parent 8e1ae36 commit 23e422e
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 52 deletions.
45 changes: 44 additions & 1 deletion build.clj
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
(ns build
(:require [clojure.tools.build.api :as b]))
(:require [clojure.tools.build.api :as b]
[clojure.java.io :as io]
[clojure.string :as str])
(:import [java.security MessageDigest]
[java.math BigInteger]
[java.nio.file Paths]))

(def ^:private TARGET-DIR "target")
(def ^:private CLASS-DIR (format "%s/classes" TARGET-DIR))
Expand All @@ -25,10 +30,48 @@
:basis @basis
:main main-ns}))

(defn- md5
[^String s]
(->> (.getBytes s)
(.digest (MessageDigest/getInstance "MD5"))
(BigInteger. 1)
(format "%032x")))


(defn- join-path
[p & ps]
(str (.normalize (Paths/get p (into-array String ps)))))


(defn- file-name-with-hash
[content-hash file-name-in-html]
(let [file-name-split (str/split file-name-in-html #"\.")
new-file-name-split (-> file-name-split
(butlast)
(concat [content-hash (last file-name-split)]))]
(str/join "." new-file-name-split)))


(defn- hash-css
"Rename css file in html with hash of the file."
[{:keys [output-file-path file-name-in-html html-file-path]
:or {html-file-path "resources/public/index.html"}}]
(let [output-file (io/file output-file-path)
new-file-name (-> (slurp output-file)
(md5)
(file-name-with-hash file-name-in-html))
new-file-path (join-path (.getParent output-file) new-file-name)
html (slurp html-file-path)]
(.renameTo output-file (io/file new-file-path))
(->> (str/replace html file-name-in-html new-file-name)
(spit html-file-path))))

(defn build
"Build an uberjar."
[_]
(clean)
(hash-css {:output-file-path "resources/public/css/output-prod.css"
:file-name-in-html "output.css"})
(uber {:uber-file UBER-FILE
:class-dir CLASS-DIR
:main-ns MAIN-NS}))
6 changes: 1 addition & 5 deletions shadow-cljs.edn
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,7 @@
:devtools {:watch-dir "resources/public"
:watch-path "/assets"
:after-load ui.main/render!}
:release {:build-hooks [; Update file name in index.html with hash
(api.util.build/hash-css
{:output-file-path "resources/public/css/output-prod.css"
:file-name-in-html "output.css"})
; Update js file name in index.html with hash
:release {:build-hooks [; Update js file name in index.html with hash
(shadow.html/copy-file
"resources/public/index.html"
"resources/public/index.html")]}}}}
46 changes: 0 additions & 46 deletions src/clj/api/util/build.clj

This file was deleted.

0 comments on commit 23e422e

Please sign in to comment.