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
|
-- | Once a target is compiled, the user usually wants to save it to the disk.
-- This is where the 'Routes' type comes in; it determines where a certain
-- target should be written.
--
-- Suppose we have an item @foo\/bar.markdown@. We can render this to
-- @foo\/bar.html@ using:
--
-- > route "foo/bar.markdown" (setExtension ".html")
--
-- If we do not want to change the extension, we can use 'idRoute', the simplest
-- route available:
--
-- > route "foo/bar.markdown" idRoute
--
-- That will route @foo\/bar.markdown@ to @foo\/bar.markdown@.
--
-- Note that the extension says nothing about the content! If you set the
-- extension to @.html@, it is your own responsibility to ensure that the
-- content is indeed HTML.
--
-- Finally, some special cases:
--
-- * If there is no route for an item, this item will not be routed, so it will
-- not appear in your site directory.
--
-- * If an item matches multiple routes, the first rule will be chosen.
--
module Hakyll.Core.Routes
( Routes
, runRoutes
, idRoute
, setExtension
, ifMatch
, customRoute
) where
import Data.Monoid (Monoid, mempty, mappend)
import Control.Monad (mplus)
import System.FilePath (replaceExtension)
import Hakyll.Core.Identifier
import Hakyll.Core.Identifier.Pattern
-- | Type used for a route
--
newtype Routes = Routes {unRoutes :: Identifier -> Maybe FilePath}
instance Monoid Routes where
mempty = Routes $ const Nothing
mappend (Routes f) (Routes g) = Routes $ \id' -> f id' `mplus` g id'
-- | Apply a route to an identifier
--
runRoutes :: Routes -> Identifier -> Maybe FilePath
runRoutes = unRoutes
-- | A route that uses the identifier as filepath. For example, the target with
-- ID @foo\/bar@ will be written to the file @foo\/bar@.
--
idRoute :: Routes
idRoute = Routes $ Just . toFilePath
-- | Set (or replace) the extension of a route.
--
-- Example:
--
-- > runRoute (setExtension "html") "foo/bar"
--
-- Result:
--
-- > Just "foo/bar.html"
--
-- Example:
--
-- > runRoute (setExtension "html") "posts/the-art-of-trolling.markdown"
--
-- Result:
--
-- > Just "posts/the-art-of-trolling.html"
--
setExtension :: String -> Routes
setExtension extension = Routes $ fmap (`replaceExtension` extension)
. unRoutes idRoute
-- | Modify a route: apply the route if the identifier matches the given
-- pattern, fail otherwise.
--
ifMatch :: Pattern -> Routes -> Routes
ifMatch pattern (Routes route) = Routes $ \id' ->
if doesMatch pattern id' then route id'
else Nothing
-- | Create a custom route. This should almost always be used with 'ifMatch'.
--
customRoute :: (Identifier -> FilePath) -> Routes
customRoute f = Routes $ Just . f
|