summaryrefslogtreecommitdiff
path: root/src/Hakyll/Check.hs
blob: 8bfc2aaf60968769b83c5f3a758307f82e7c48f9 (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
--------------------------------------------------------------------------------
{-# LANGUAGE CPP               #-}
{-# LANGUAGE OverloadedStrings #-}
module Hakyll.Check
    ( Check (..)
    , check
    ) where


--------------------------------------------------------------------------------
import           Control.Monad                (forM_)
import           Control.Monad.Reader         (ask)
import           Control.Monad.RWS            (RWST, runRWST)
import           Control.Monad.Trans          (liftIO)
import           Control.Monad.Trans.Resource (runResourceT)
import           Control.Monad.Writer         (tell)
import           Data.List                    (isPrefixOf)
import           Data.Set                     (Set)
import qualified Data.Set                     as S
import           Network.URI                  (unEscapeString)
import           System.Directory             (doesDirectoryExist,
                                               doesFileExist)
import           System.Exit                  (ExitCode (..))
import           System.FilePath              (takeDirectory, takeExtension,
                                               (</>))
import qualified Text.HTML.TagSoup            as TS


--------------------------------------------------------------------------------
#ifdef CHECK_EXTERNAL
import           Control.Exception            (AsyncException (..),
                                               SomeException (..), handle,
                                               throw)
import           Control.Monad.State          (get, modify)
import           Data.List                    (intercalate)
import           Data.Typeable                (cast)
import           Data.Version                 (versionBranch)
import           GHC.Exts                     (fromString)
import qualified Network.HTTP.Conduit         as Http
import qualified Network.HTTP.Types           as Http
import qualified Paths_hakyll                 as Paths_hakyll
#endif


--------------------------------------------------------------------------------
import           Hakyll.Core.Configuration
import           Hakyll.Core.Logger           (Logger)
import qualified Hakyll.Core.Logger           as Logger
import           Hakyll.Core.Util.File
import           Hakyll.Web.Html


--------------------------------------------------------------------------------
data Check = All | InternalLinks
    deriving (Eq, Ord, Show)


--------------------------------------------------------------------------------
check :: Configuration -> Logger -> Check -> IO ExitCode
check config logger check' = do
    ((), write) <- runChecker checkDestination config logger check'
    return $ if checkerFaulty write > 0 then ExitFailure 1 else ExitSuccess


--------------------------------------------------------------------------------
data CheckerRead = CheckerRead
    { checkerConfig :: Configuration
    , checkerLogger :: Logger
    , checkerCheck  :: Check
    }


--------------------------------------------------------------------------------
data CheckerWrite = CheckerWrite
    { checkerFaulty :: Int
    , checkerOk     :: Int
    } deriving (Show)


--------------------------------------------------------------------------------
instance Monoid CheckerWrite where
    mempty                                            = CheckerWrite 0 0
    mappend (CheckerWrite f1 o1) (CheckerWrite f2 o2) =
        CheckerWrite (f1 + f2) (o1 + o2)


--------------------------------------------------------------------------------
type CheckerState = Set String


--------------------------------------------------------------------------------
type Checker a = RWST CheckerRead CheckerWrite CheckerState IO a


--------------------------------------------------------------------------------
runChecker :: Checker a -> Configuration -> Logger -> Check
           -> IO (a, CheckerWrite)
runChecker checker config logger check' = do
    let read' = CheckerRead
                    { checkerConfig = config
                    , checkerLogger = logger
                    , checkerCheck  = check'
                    }

    (x, _, write) <- runRWST checker read' S.empty
    Logger.flush logger
    return (x, write)


--------------------------------------------------------------------------------
checkDestination :: Checker ()
checkDestination = do
    config <- checkerConfig <$> ask
    files  <- liftIO $ getRecursiveContents
        (const $ return False) (destinationDirectory config)

    let htmls =
            [ destinationDirectory config </> file
            | file <- files
            , takeExtension file == ".html"
            ]

    forM_ htmls checkFile


--------------------------------------------------------------------------------
checkFile :: FilePath -> Checker ()
checkFile filePath = do
    logger   <- checkerLogger <$> ask
    contents <- liftIO $ readFile filePath
    Logger.header logger $ "Checking file " ++ filePath

    let urls = getUrls $ TS.parseTags contents
    forM_ urls $ \url -> do
        Logger.debug logger $ "Checking link " ++ url
        checkUrl filePath url


--------------------------------------------------------------------------------
checkUrl :: FilePath -> String -> Checker ()
checkUrl filePath url
    | isExternal url  = checkExternalUrl url
    | hasProtocol url = skip "Unknown protocol, skipping"
    | otherwise       = checkInternalUrl filePath url
  where
    validProtoChars = ['A'..'Z'] ++ ['a'..'z'] ++ ['0'..'9'] ++ "+-."
    hasProtocol str = case break (== ':') str of
        (proto, ':' : _) -> all (`elem` validProtoChars) proto
        _                -> False


--------------------------------------------------------------------------------
ok :: String -> Checker ()
ok _ = tell $ mempty {checkerOk = 1}


--------------------------------------------------------------------------------
skip :: String -> Checker ()
skip reason = do
    logger <- checkerLogger <$> ask
    Logger.debug logger $ reason
    tell $ mempty {checkerOk = 1}

--------------------------------------------------------------------------------
faulty :: String -> Checker ()
faulty url = do
    logger <- checkerLogger <$> ask
    Logger.error logger $ "Broken link to " ++ show url
    tell $ mempty {checkerFaulty = 1}


--------------------------------------------------------------------------------
checkInternalUrl :: FilePath -> String -> Checker ()
checkInternalUrl base url = case url' of
    "" -> ok url
    _  -> do
        config <- checkerConfig <$> ask
        let dest = destinationDirectory config
            dir  = takeDirectory base
            filePath
                | "/" `isPrefixOf` url' = dest ++ url'
                | otherwise             = dir </> url'

        exists <- checkFileExists filePath
        if exists then ok url else faulty url
  where
    url' = stripFragments $ unEscapeString url


--------------------------------------------------------------------------------
checkExternalUrl :: String -> Checker ()
#ifdef CHECK_EXTERNAL
checkExternalUrl url = do
    logger     <- checkerLogger           <$> ask
    needsCheck <- (== All) . checkerCheck <$> ask
    checked    <- (url `S.member`)        <$> get

    if not needsCheck || checked
        then Logger.debug logger "Already checked, skipping"
        else do
            isOk <- liftIO $ handle (failure logger) $ do
                mgr <- Http.newManager Http.tlsManagerSettings
                runResourceT $ do
                    request  <- Http.parseUrl urlToCheck
                    response <- Http.http (settings request) mgr
                    let code = Http.statusCode (Http.responseStatus response)
                    return $ code >= 200 && code < 300

            modify $ if schemeRelative url
                         then S.insert urlToCheck . S.insert url
                         else S.insert url
            if isOk then ok url else faulty url
  where
    -- Add additional request info
    settings r = r
        { Http.method         = "HEAD"
        , Http.redirectCount  = 10
        , Http.requestHeaders = ("User-Agent", ua) : Http.requestHeaders r
        }

    -- Nice user agent info
    ua = fromString $ "hakyll-check/" ++
        (intercalate "." $ map show $ versionBranch $ Paths_hakyll.version)

    -- Catch all the things except UserInterrupt
    failure logger (SomeException e) = case cast e of
        Just UserInterrupt -> throw UserInterrupt
        _                  -> Logger.error logger (show e) >> return False

    -- Check scheme-relative links
    schemeRelative = isPrefixOf "//"
    urlToCheck     = if schemeRelative url then "http:" ++ url else url
#else
checkExternalUrl _ = return ()
#endif



--------------------------------------------------------------------------------
-- | Wraps doesFileExist, also checks for index.html
checkFileExists :: FilePath -> Checker Bool
checkFileExists filePath = liftIO $ do
    file <- doesFileExist filePath
    dir  <- doesDirectoryExist filePath
    case (file, dir) of
        (True, _) -> return True
        (_, True) -> doesFileExist $ filePath </> "index.html"
        _         -> return False


--------------------------------------------------------------------------------
stripFragments :: String -> String
stripFragments = takeWhile (not . flip elem ['?', '#'])