Created
October 5, 2012 02:58
-
-
Save gregwebs/3837808 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$with scripts <- ["Prelude", "Config", "KV"] | |
^{combineScripts "app" scripts} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
renderHamlet ∷ Bool → (Text → Text → Sh FilePath) → Text | |
renderHamlet isDebug hasher = | |
let hashedFile fp = toTextIgnore $ | |
if isDebug then fp else unsafePerformIO $ shelly $ do | |
contents ← readfile fp | |
hasher (LT.fromStrict $ fromJust $ extension fp) contents | |
in renderHtml $(hamletFile "combine.html.hamlet") | |
where | |
combineScripts path = (mkScripts ∘ map encodeString) ∘ | |
(if isDebug then id else unsafePerformIO ∘ combine "js") ∘ map (λfp → path </> fp <.> "js") | |
where | |
mkScripts scripts = [hamletN|$forall script <- scripts | |
<script type=text/javascript src=#{script}> | |
|] | |
combine ∷ Text → [FilePath] → IO [FilePath] | |
combine ext files = shelly $ do | |
contents ← mapM readfile files | |
let content = LT.concat contents | |
fmap (:[]) $ hasher ext content | |
hashedFile ∷ Text → Text → Sh FilePath | |
hashedFile ext orig = shelly $ do | |
(hashedName, content) ← hashedFileWithContents ext orig | |
let newName = (if ext ≡ "js" then "scripts" else "resources/css") </> hashedName | |
writefile (deploy_dir </> newName) content | |
return newName | |
hashedFileWithContents ∷ Text → Text → Sh (FilePath, Text) | |
hashedFileWithContents ext orig = do | |
contents ← if ext ≡ "js" then uglify orig else return orig | |
let hashed = hashContents contents | |
return (hashed `addExtension` LT.toStrict ext, contents) | |
uglify :: Text -> Sh Text | |
uglify contents = do | |
setStdin contents | |
print_stdout False $ cmd "../vendor/node_modules/uglify-js/bin/uglifyjs" "" | |
-- from yesod-static | |
hashContents ∷ Text → FilePath | |
hashContents = decodeString ∘ base64 ∘ hash ∘ TE.encodeUtf8 ∘ LT.toStrict | |
where | |
base64 ∷ ByteString → String | |
base64 = map tr | |
∘ take 8 | |
∘ S8.unpack | |
∘ Data.ByteString.Base64.encode | |
where | |
tr '+' = '-' | |
tr '/' = '_' | |
tr c = c | |
-- use: | |
renderHamlet True undefined -- development | |
renderHamlet False hashedFile -- production |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment