-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsite.hs
290 lines (240 loc) · 10.4 KB
/
site.hs
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
288
289
290
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralisedNewtypeDeriving #-}
import Data.Dynamic (toDyn)
import Data.Functor (($>))
import Data.Foldable (for_)
import Data.Functor.Identity (Identity(runIdentity))
import Data.List (isPrefixOf)
import Data.Maybe (fromMaybe, listToMaybe)
import Data.Monoid (First(..), Last(..))
import Data.Text (Text)
import qualified Data.Text as Text
import qualified Data.Text.Lazy as Text.Lazy
import qualified Data.Time as Time
import Data.Traversable (for)
import qualified Data.Tree as Tree
import System.Environment (getArgs)
import Debug.Trace
import qualified Text.Blaze.Html as Blaze
import qualified Text.Blaze.Html.Renderer.Text as Blaze
import qualified Commonmark as Md
import qualified Commonmark.Blocks as Md
import qualified Commonmark.Extensions as Md
import qualified Commonmark.Tokens as Md
import qualified Commonmark.TokParsers as Md
import Hakyll
import qualified Skylighting
import Text.Parsec ((<|>))
import qualified Text.Parsec as Parsec
import qualified Text.Parsec.Char as Parsec
--------------------------------------------------------------------------------
main :: IO ()
main = do
command <- fromMaybe "" . listToMaybe <$> getArgs
let postsPattern = postsPatternForCommand command
metadataMatcher <- metadataMatcherForCommand command
hakyll $ do
match "favicon.ico" $ do
route idRoute
compile copyFileCompiler
match "images/**" $ do
route idRoute
compile copyFileCompiler
match "Benjamin_Hodgson_CV.pdf" $ do
route idRoute
compile copyFileCompiler
match "css/*" $ do
compile getResourceBody
match "js/**" $ do
route idRoute
compile getResourceBody
create ["all.css"] $ do
route idRoute
compile $ do
items <- loadAll "css/*"
makeItem $ compressCss $ concatMap itemBody items
for_ ["about.md", "404.md"] $ \pat -> match pat $ do
route $ setExtension "html"
compile $ commonmarkCompiler
>>= loadAndApplyTemplate "templates/default.html" defaultContext
>>= relativizeUrls
matchMetadata postsPattern metadataMatcher $ do
route $ setExtension "html"
compile $
commonmarkCompiler
>>= loadAndApplyTemplate "templates/post.html" postCtx
>>= saveSnapshot "content"
>>= loadAndApplyTemplate "templates/default.html" postCtx
>>= relativizeUrls
version "redirects" $ createRedirects [
("posts/2018-03-10-eighty.html", "2018-03-16-eighty.html"),
("posts/2019-12-22-building-prolog's-rules-engine.html", "2019-12-22-building-prologs-rules-engine.html")
]
create ["atom.xml"] $ do
route idRoute
compile $
loadAllSnapshots postsPattern "content"
>>= recentFirst
>>= renderAtom feedConfig atomCtx
match "index.html" $ do
route idRoute
compile $ do
posts <- recentFirst =<< loadAll postsPattern
let indexCtx =
listField "posts" postCtx (return posts) `mappend`
defaultContext
getResourceBody
>>= applyAsTemplate indexCtx
>>= loadAndApplyTemplate "templates/default.html" indexCtx
>>= relativizeUrls
match "templates/*" $ compile templateCompiler
--------------------------------------------------------------------------------
postsPatternForCommand "watch" = "posts/*" .&&. hasNoVersion .||. "drafts/*"
postsPatternForCommand _ = "posts/*" .&&. hasNoVersion
metadataMatcherForCommand "watch" = return (const True)
metadataMatcherForCommand _ = do
time <- Time.getCurrentTime
return $ \metadata ->
case parseDate <$> lookupString "date" metadata of
Just date -> date < time
_ -> False
parseDate = Time.parseTimeOrError True Time.defaultTimeLocale "%Y-%m-%d"
postCtx :: Context String
postCtx =
dateField "date" "%Y-%m-%d" `mappend`
dateField "englishDate" "%B %e, %Y" `mappend`
defaultContext
atomCtx :: Context String
atomCtx =
postCtx `mappend`
bodyField "description"
feedConfig = FeedConfiguration {
feedTitle = "benjamin.pizza",
feedDescription = "Benjamin's blog",
feedAuthorName = "Benjamin Hodgson",
feedAuthorEmail = "[email protected]",
feedRoot = "http://www.benjamin.pizza"
}
commonmarkCompiler :: Compiler (Item String)
commonmarkCompiler = cached "Benjamin.Pizza.commonmarkCompiler" $ do
body <- fmap Text.pack <$> getResourceBody
path <- getResourceFilePath
for body $ \md -> case runIdentity $ Md.commonmarkWith benjaminFlavouredMarkdown path md of
Left err -> fail (show err)
Right (Html html) -> return $ Text.Lazy.unpack (Md.renderHtml html)
newtype Html = Html { getHtml :: Md.Html () }
deriving (
Show,
Semigroup,
Monoid,
Md.Rangeable,
Md.HasAttributes,
Md.IsInline,
Md.HasQuoted,
Md.HasStrikethrough,
Md.ToPlainText
)
instance Md.HasFootnote Html Html where
footnote num txt = Html . Md.footnote num txt . getHtml
footnoteList = Html . Md.footnoteList . map getHtml
footnoteRef num txt = Html . Md.footnoteRef num txt . getHtml
instance Md.IsBlock Html Html where
paragraph = Html . Md.paragraph . getHtml
plain = Html . Md.plain . getHtml
thematicBreak = Html Md.thematicBreak
blockQuote = Html . Md.blockQuote . getHtml
codeBlock = highlightCodeBlock
heading lvl = Html . Md.heading lvl . getHtml
rawBlock fmt txt = Html (Md.rawBlock fmt txt)
referenceLinkDefinition txt info = Html (Md.referenceLinkDefinition txt info)
list ty spacing = Html . Md.list ty spacing . map getHtml
benjaminFlavouredMarkdown :: Md.SyntaxSpec Identity Html Html
benjaminFlavouredMarkdown = mconcat [
Md.smartPunctuationSpec,
Md.strikethroughSpec,
Md.attributesSpec,
Md.autoIdentifiersAsciiSpec,
Md.footnoteSpec,
Md.implicitHeadingReferencesSpec,
calloutSpec,
linkifyHeadersSpec,
Md.defaultSyntaxSpec
]
calloutSpec :: Md.SyntaxSpec Identity Html Html
calloutSpec = mempty { Md.syntaxFinalParsers = [modifyCallouts] }
modifyCallouts :: Md.BlockParser Identity Html Html Html
modifyCallouts = do
Parsec.updateState $ \st -> st { Md.nodeStack = [transformTree setCallout t | t <- Md.nodeStack st] }
return mempty
where
setCallout bn
| Md.blockType (Md.blockSpec (Tree.rootLabel bn)) == "BlockQuote" =
case getCallout bn of
Nothing -> bn
Just (calloutType, title) -> replaceTitle title $ addClass ("callout callout-" <> calloutType) bn
| otherwise = bn
getCallout bn = do
para <- listToMaybe $ Tree.subForest bn
-- Md.blockLines is in reverse order
firstLine <- listToMaybe $ reverse $ Md.blockLines $ Tree.rootLabel para
getFirst $ foldMap (First . Just) $ Parsec.runParser calloutParser () "" firstLine
calloutParser = do
Parsec.optional Md.whitespace
Md.symbol '['
Md.symbol '!'
ty <- Md.satisfyWord (const True) -- a single word
Md.symbol ']'
title <- Md.restOfLine
let title' = if Md.WordChars `elem` [Md.tokType t | t <- title]
then title
else [ty { Md.tokContents = Text.toTitle (Md.tokContents ty) }]
return (Md.tokContents ty, title')
-- strip the [!type] line and replace it with an h3
replaceTitle title (Tree.Node bd (t:ts)) =
-- Md.blockLines is in reverse order
let remainingLines = init $ Md.blockLines $ Tree.rootLabel t
newT = t { Tree.rootLabel = (Tree.rootLabel t) { Md.blockLines = remainingLines } }
newH3 = (Md.defBlockData Md.atxHeadingSpec) {
Md.blockLines = [title],
Md.blockData = toDyn (3 :: Int),
Md.blockStartPos = Md.blockStartPos bd
}
in Tree.Node bd (Tree.Node newH3 [] : newT : ts)
replaceTitle _ _ = error "Can't happen"
addClass cls bn =
let newAttrs = addClassToAttrs cls (Md.blockAttributes (Tree.rootLabel bn))
in bn { Tree.rootLabel = (Tree.rootLabel bn) { Md.blockAttributes = newAttrs } }
addClassToAttrs cls [] = [("class", cls)]
addClassToAttrs cls (("class", oldCls):attrs) = ("class", oldCls <> " " <> cls) : attrs
addClassToAttrs cls (attr:attrs) = attr : addClassToAttrs cls attrs
transformTree :: (Tree.Tree a -> Tree.Tree a) -> Tree.Tree a -> Tree.Tree a
transformTree f t = f (t { Tree.subForest = map (transformTree f) (Tree.subForest t) })
linkifyHeadersSpec :: Md.SyntaxSpec Identity Html Html
linkifyHeadersSpec = mempty { Md.syntaxFinalParsers = [linkifyHeaders] }
linkifyHeaders :: Md.BlockParser Identity Html Html Html
linkifyHeaders = do
Parsec.updateState $ \st -> st { Md.nodeStack = [fmap setLink t | t <- Md.nodeStack st] }
return mempty
where
setLink bd
| Md.blockType (Md.blockSpec bd) `elem` ["ATXHeading", "SetextHeading"] =
case lookup "id" (Md.blockAttributes bd) of
Nothing -> bd
Just ident -> bd { Md.blockLines = addLink (Md.blockLines bd) ident }
| otherwise = bd
addLink [line@(t1:_)] ident =
let l = Text.strip (Md.untokenize line)
newLine = "[" <> l <> "](#" <> ident <> ")"
in [Md.tokenize "" newLine]
addLink lines _ = lines
sym s loc = Md.Tok (Md.Symbol s) loc (Text.singleton s)
highlightCodeBlock :: Text -> Text -> Html
highlightCodeBlock lang txt =
let result = do
syntax <- Skylighting.lookupSyntax lang Skylighting.defaultSyntaxMap
lines <- foldMap Just $ Skylighting.tokenize defaultTokeniserConfig syntax txt
return $ Skylighting.formatHtmlBlock Skylighting.defaultFormatOpts lines
in case result of
Just blaze -> Html $ Md.htmlRaw $ Text.Lazy.toStrict $ Blaze.renderHtml blaze
Nothing -> Html $ Md.codeBlock lang txt
defaultTokeniserConfig = Skylighting.TokenizerConfig Skylighting.defaultSyntaxMap False