summaryrefslogtreecommitdiff
path: root/src/Main.hs
blob: fac40acbb63e88cd2e873ed21e4c2b1bb11bc101 (plain)
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}

module Main where

import Control.Monad (forM)
import Data.List (isSuffixOf)
import Data.Time.Format (formatTime, FormatTime)
import Data.Time.Locale.Compat (defaultTimeLocale)
import Hakyll.Core.Compiler
    ( Compiler
    , load
    , loadAllSnapshots
    , makeItem
    , noResult
    , saveSnapshot
    , getResourceBody
    )
import Hakyll.Core.Configuration (Configuration(..))
import Hakyll.Core.File (copyFileCompiler)
import Hakyll.Core.Identifier (Identifier(..), fromFilePath, toFilePath)
import Hakyll.Core.Identifier.Pattern (Pattern, fromCapture, fromGlob)
import Hakyll.Core.Item (Item(..))
import Hakyll.Core.Metadata (getMetadataField)
import Hakyll.Main (hakyllWith)
import Hakyll.Core.Routes (Routes, customRoute, idRoute)
import Hakyll.Core.Rules
    ( Rules
    , compile
    , route
    , match
    )
import Hakyll.Web.CompressCss (compressCssCompiler)
import Hakyll.Web.Html (demoteHeaders, withUrls)
import Hakyll.Web.Paginate (buildPaginateWith, paginateContext, paginateEvery, paginateRules)
import Hakyll.Web.Pandoc
    ( defaultHakyllReaderOptions
    , defaultHakyllWriterOptions
    , writePandocWith
    )
import Hakyll.Web.Pandoc.Biblio (biblioCompiler, cslCompiler, readPandocBiblio)
import Hakyll.Web.Tags (Tags(..), buildTags, tagsRules)
import Hakyll.Web.Template (loadAndApplyTemplate, templateBodyCompiler)
import Hakyll.Web.Template.Context
    ( Context(..)
    , ContextField(..)
    , bodyField
    , boolField
    , constField
    , defaultContext
    , listField
    , listFieldWith
    , field
    , teaserField
    , getItemUTC
    )
import Hakyll.Web.Template.List (recentFirst, sortRecentFirst)
import System.FilePath
    ( addTrailingPathSeparator
    , joinPath
    , replaceExtension
    , splitDirectories
    , takeDirectory
    )
import System.Process (rawSystem)
import qualified Network.Wai.Application.Static as Static
import Text.Pandoc.Options (HTMLMathMethod(..), WriterOptions(..))

--
--
-- Default configuration.
--
configuration :: Configuration
configuration = Configuration
    { destinationDirectory = "./var/web"
    , storeDirectory = "./var/cache"
    , tmpDirectory = "./var/cache/tmp"
    , providerDirectory = "./themes"
    , watchIgnore = const False
    , ignoreFile = const False
    , deployCommand = "rsync"
    , deploySite = deploySite'
    , inMemoryCache = True
    , previewHost = "127.0.0.1"
    , previewPort = 8000
    , checkHtmlFile = const False
    , previewSettings = Static.defaultFileServerSettings
    }
  where
    deploySite'  deploymentConfiguration
        = readFile "deployment.txt"
        >>= executeDeployment deploymentConfiguration
    executeDeployment Configuration{..} deploymentTarget = rawSystem deployCommand
        [ "-ave"
        , "ssh"
        , "--delete"
        , addTrailingPathSeparator destinationDirectory
        , deploymentTarget
        ]

--
-- Helpers.
--
createIndex :: Tags -> Rules ()
createIndex tags = do
    paginate <- buildPaginateWith grouper "posts/**" makeId
    paginateRules paginate $ indexRules paginate
  where
    indexRules paginate pageNumber pagePattern = do
        route idRoute
        compile $ do
            posts <- recentFirst =<< loadAllSnapshots pagePattern "content"
            let context
                    = listField "posts" (postCtx tags) (pure posts)
                    <> constField "title" "Startseite"
                    <> boolField "active-blog" (const True)
                    <> paginateContext paginate pageNumber
                    <> flevumContext tags
            makeItem ""
                >>= loadAndApplyTemplate "templates/blog.html" context
                >>= loadAndApplyTemplate "templates/default.html" context
                >>= cleanIndexUrls
    makeId 1 = "index.html"
    makeId pageNumber = fromFilePath $ shows pageNumber ".html"

localizeMonth :: String -> String
localizeMonth "01" = "Januar"
localizeMonth "02" = "Februar"
localizeMonth "03" = "März"
localizeMonth "04" = "April"
localizeMonth "05" = "Mai"
localizeMonth "06" = "Juni"
localizeMonth "07" = "Juli"
localizeMonth "08" = "August"
localizeMonth "09" = "September"
localizeMonth "10" = "Oktober"
localizeMonth "11" = "November"
localizeMonth "12" = "Dezember"
localizeMonth _ = error "Invalid month number"

formatDate :: FormatTime t => t -> String
formatDate time
    = formatDefaultLocale "%e. "
    ++ localizeMonth (formatDefaultLocale "%m")
    ++ formatDefaultLocale " %Y"
  where
    formatDefaultLocale :: String -> String
    formatDefaultLocale = flip (formatTime defaultTimeLocale) time

postCtx :: Tags -> Context String
postCtx tags
    = field "published" dateField'
    <> teaserField "teaser" "content"
    <> bodyField "description"
    <> flevumContext tags
  where
    dateField' :: Item String -> Compiler String
    dateField' = fmap formatDate
        . getItemUTC defaultTimeLocale
        . itemIdentifier

flevumContext :: Tags -> Context String
flevumContext = (<> defaultContext) . tagsCloud

tagsCloud :: Tags -> Context String
tagsCloud tags
    = listFieldWith "categories" (Context categoryContextF)
    $ forM (tagsMap tags) . go
  where
    categoryContextF "title" _ = pure . StringField . categoryTitle
    categoryContextF "url" _ = pure . StringField . ("/" ++) . categoryTitle
    categoryContextF "body" _ = pure . StringField . itemBody
    categoryContextF key _ = const $ noResult $ "Tried field " ++ key
    categoryTitle = last . directoryNames . itemIdentifier
    directoryNames = init . splitDirectories .toFilePath
    go :: Item String -> (String, [Identifier]) -> Compiler (Item FilePath)
    go Item{ itemIdentifier = currentPage } tag = do
        let tagId = tagsMakeId tags $ fst tag
        tagsMetadata <- getMetadataField currentPage "tags"
        let isActiveClass
                = directoryNames currentPage == directoryNames tagId
                || Just (fst tag) == tagsMetadata
        pure $ Item tagId $ if isActiveClass then "active" else ""

withoutRootRoute :: Routes
withoutRootRoute = customRoute
    $ joinPath
    . drop 1 -- posts/
    . splitDirectories
    . flip replaceExtension "html"
    . toFilePath

cleanIndexUrls :: Item String -> Compiler (Item String)
cleanIndexUrls = return . fmap (withUrls cleanIndex)
  where
    cleanIndex url
        | "/index.html" `isSuffixOf` url = takeDirectory url
        | otherwise = url

bibtexCompiler :: Compiler (Item String)
bibtexCompiler = do 
    bib <- load "assets/bibliography/references.bib"
    csl <- load "assets/bibliography/theologie-und-philosophie.csl"

    let pandocBiblio = readPandocBiblio defaultHakyllReaderOptions csl bib
        writerOptions = defaultHakyllWriterOptions
            { writerHTMLMathMethod = MathML
            }

    fmap demoteHeaders . writePandocWith writerOptions
        <$> (getResourceBody >>= pandocBiblio)

copyMatchedFiles :: Pattern -> Rules ()
copyMatchedFiles = flip match $ route idRoute >> compile copyFileCompiler

grouper :: [Identifier] -> Rules [[Identifier]]
grouper = fmap (paginateEvery 25) . sortRecentFirst

createTagPage :: Tags -> String -> Pattern -> Rules ()
createTagPage tags tagName tagPattern = do
    paginate <- buildPaginateWith grouper tagPattern makeId
    paginateRules paginate $ paginateTag paginate
  where
    paginateTag paginate pageNumber pagePattern = do
        route withoutRootRoute
        compile $ do
            posts <- recentFirst =<< loadAllSnapshots pagePattern "content"
            let context = listField "posts" (postCtx tags) (pure posts)
                    <> constField "title" tagName
                    <> paginateContext paginate pageNumber
                    <> flevumContext tags

            makeItem ""
                >>= loadAndApplyTemplate "templates/tag.html" context
                >>= loadAndApplyTemplate "templates/default.html" context
    tagBase = fromFilePath . (("tags/" ++ tagName) ++)
    makeId 1 = tagBase "/index.html"
    makeId pageNumber = tagBase ('/' : shows pageNumber ".html")

--
-- Hakyll rules.
--
rules :: Rules ()
rules = do
    tags <- buildTags "posts/**" (fromCapture "tags/*/index.html")
    let contextWithTags = flevumContext tags

    -- Home page.
    createIndex tags

    -- Bottom menu.
    match "pages/*.tex" $ do
        route withoutRootRoute
        compile $ bibtexCompiler
            >>= loadAndApplyTemplate "templates/page.html" contextWithTags
            >>= loadAndApplyTemplate "templates/default.html" contextWithTags
            >>= cleanIndexUrls

    -- Categories.
    tagsRules tags $ createTagPage tags

    -- Blog posts.
    match "posts/**.tex" $ do
        route withoutRootRoute
        compile $ bibtexCompiler
            >>= saveSnapshot "content"
            >>= loadAndApplyTemplate "templates/post.html" (postCtx tags)
            >>= loadAndApplyTemplate "templates/default.html" (postCtx tags)
            >>= cleanIndexUrls

    match "assets/bibliography/*.bib" $ compile biblioCompiler
    match "assets/bibliography/*.csl" $ compile cslCompiler

    -- Templates.
    match (fromGlob "templates/*") $ compile templateBodyCompiler
    match "_includes/**" $ compile templateBodyCompiler

    -- Copy files.
    copyMatchedFiles "assets/fonts/*"
    copyMatchedFiles "assets/images/**"

    match "assets/css/*.css"
        $ route idRoute
        >> compile compressCssCompiler

main :: IO ()
main = hakyllWith configuration rules