utilities.hs 27.3 KB
Newer Older
Henrik Tramberend's avatar
Henrik Tramberend committed
1
module Utilities
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
  ( calcProjectDirectory
  , spawn
  , terminate
  , threadDelay'
  , wantRepeat
  , waitForModificationIn
  , defaultContext
  , runShakeInContext
  , watchFiles
  , waitForTwitch
  , dropSuffix
  , stopServer
  , startServer
  , runHttpServer
  , writeIndex
  , readMetaData
  , readMetaDataForDir
  , readMetaDataIO
  , substituteMetaData
  , markdownToHtmlDeck
  , markdownToHtmlHandout
  , markdownToPdfHandout
  , markdownToHtmlPage
  , markdownToPdfPage
  , writeExampleProject
  , metaValueAsString
  , (<++>)
  , markNeeded
  , replaceSuffixWith
  , writeEmbeddedFiles
  , getRelativeSupportDir
  , pandocMakePdf
  , isCacheableURI
  , adjustLocalUrl
  , cacheRemoteFile
  , cacheRemoteImages
  , makeRelativeTo
  , fixMustacheMarkup
  , fixMustacheMarkupText
  , globA
  , globRelA
  , DeckerException(..)
  ) where
Henrik Tramberend's avatar
Henrik Tramberend committed
45 46 47 48 49 50

import Control.Monad.Loops
import Control.Monad
import Control.Concurrent
import Control.Exception
import Development.Shake
51
import Development.Shake.FilePath as SFP
52
import Data.Dynamic
Henrik Tramberend's avatar
Henrik Tramberend committed
53 54 55
import Data.List.Extra
import Data.Maybe
import Data.IORef
Henrik Tramberend's avatar
Henrik Tramberend committed
56
import qualified Data.HashMap.Strict as H
Henrik Tramberend's avatar
Henrik Tramberend committed
57
import qualified Data.Text as T
58
import qualified Data.Text.Encoding as E
Henrik Tramberend's avatar
Henrik Tramberend committed
59 60 61 62 63 64 65
import Data.Time.Clock
import Data.Typeable
import qualified Data.Set as Set
import qualified Data.HashMap.Lazy as HashMap
import Text.Printf
import System.Process
import System.Process.Internals
66
import System.Directory as Dir
Henrik Tramberend's avatar
Henrik Tramberend committed
67
import System.Exit
68
import System.FilePath as SF
Henrik Tramberend's avatar
Henrik Tramberend committed
69
import System.FilePath.Glob
Henrik Tramberend's avatar
Henrik Tramberend committed
70 71 72 73 74 75
import qualified Data.Yaml as Y
import qualified Text.Mustache as M
import qualified Text.Mustache.Types as MT
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy as LB
import qualified Data.ByteString.Lazy.Char8 as L8
Henrik Tramberend's avatar
Henrik Tramberend committed
76
import Data.Digest.Pure.MD5
Henrik Tramberend's avatar
Henrik Tramberend committed
77 78 79 80 81 82 83 84
import Text.Pandoc
import Text.Pandoc.Walk
import Text.Pandoc.PDF
import Text.CSL.Pandoc
import Filter
import Debug.Trace
import Network.HTTP.Conduit
import Network.HTTP.Simple
Henrik Tramberend's avatar
Henrik Tramberend committed
85
import Network.HTTP.Types.Status
Henrik Tramberend's avatar
Henrik Tramberend committed
86 87
import Network.URI
import Text.Highlighting.Kate.Styles
88
import Context
89
import Embed
90

91 92
-- Find the project directory and change current directory to there. 
-- The project directory is the first upwards directory that contains a .git directory entry.
93
calcProjectDirectory :: IO FilePath
94 95 96 97 98 99 100 101 102 103 104 105 106
calcProjectDirectory = do
  cwd <- getCurrentDirectory
  searchGitRoot cwd
  where
    searchGitRoot :: FilePath -> IO FilePath
    searchGitRoot path =
      if isDrive path
        then makeAbsolute "."
        else do
          hasGit <- Dir.doesDirectoryExist (path </> ".git")
          if hasGit
            then makeAbsolute path
            else searchGitRoot $ takeDirectory path
Henrik Tramberend's avatar
Henrik Tramberend committed
107

108 109 110
-- | Globs for files under the project dir in the Action monad. 
-- Returns absolute pathes. 
globA :: FilePattern -> Action [FilePath]
111 112 113
globA pattern = do
  projectDir <- getProjectDir
  liftIO $ globDir1 (compile pattern) projectDir
114 115 116 117

-- | Globs for files under the project dir in the Action monad. 
-- Returns pathes relative to the project directory. 
globRelA :: FilePattern -> Action [FilePath]
118 119 120 121
globRelA pattern = do
  projectDir <- getProjectDir
  files <- globA pattern
  return $ map (makeRelative projectDir) files
122

Henrik Tramberend's avatar
Henrik Tramberend committed
123 124 125 126
-- Utility functions for shake based apps
spawn :: String -> Action ProcessHandle
spawn = liftIO . spawnCommand

127
-- Runs liveroladx on the given directory, if it is not already running. If
Henrik Tramberend's avatar
Henrik Tramberend committed
128
-- open is True a browser window is opended.
129 130 131 132 133 134 135 136 137 138 139
runHttpServer dir open = do
  process <- getServerHandle
  case process of
    Just handle -> return ()
    Nothing -> do
      putNormal "# livereloadx (on http://localhost:8888, see server.log)"
      handle <-
        spawn $ "livereloadx -s -p 8888 -d 500 " ++ dir ++ " 2>&1 > server.log"
      setServerHandle $ Just handle
      threadDelay' 200000
      when open $ cmd "open http://localhost:8888/" :: Action ()
Henrik Tramberend's avatar
Henrik Tramberend committed
140

141
startServer id command =
Henrik Tramberend's avatar
Henrik Tramberend committed
142 143 144
  liftIO $
  do processHandle <- spawnCommand command
     withProcessHandle processHandle handleResult
145 146 147 148 149 150 151 152
  where
    handleResult ph =
      case ph of
        ClosedHandle e ->
          print $ "Error starting server " ++ id ++ ": " ++ show e
        OpenHandle p -> do
          print $ "Server " ++ id ++ " running (" ++ show p ++ ")"
          writeFile (id ++ ".pid") (show p)
Henrik Tramberend's avatar
Henrik Tramberend committed
153

154
stopServer id =
Henrik Tramberend's avatar
Henrik Tramberend committed
155 156 157 158 159
  liftIO $
  do let pidFile = id ++ ".pid"
     result <- try $ readFile pidFile
     case result of
       Left (SomeException e) -> print $ "Unable to read file " ++ pidFile
160 161 162
       Right pid -> do
         exitCode <- system ("kill -9 " ++ pid)
         removeFile pidFile
Henrik Tramberend's avatar
Henrik Tramberend committed
163 164 165 166 167 168 169 170 171 172 173 174 175

terminate :: ProcessHandle -> Action ()
terminate = liftIO . terminateProcess

threadDelay' :: Int -> Action ()
threadDelay' = liftIO . threadDelay

wantRepeat :: IORef Bool -> Action ()
wantRepeat justOnce = liftIO $ writeIORef justOnce False

waitForModificationIn :: [FilePath] -> Action ()
waitForModificationIn = liftIO . waitForTwitch

176 177
-- The context of program invocation consists of a list of
-- files to watch and a possibly running local http server.
Henrik Tramberend's avatar
Henrik Tramberend committed
178 179 180 181 182 183
data Context =
  Context [FilePath]
          (Maybe ProcessHandle)

defaultContext = Context [] Nothing

184
runShakeInContext :: ActionContext -> ShakeOptions -> Rules () -> IO ()
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
runShakeInContext context options rules = do
  opts <- setActionContext context options
  catch
    (untilM_ (tryRunShake opts) nothingToWatch)
    (\(SomeException e) -> putStrLn $ "Terminated: " ++ show e)
  cleanup
  where
    tryRunShake opts =
      catch (shakeArgs opts rules) (\(SomeException e) -> return ())
    cleanup = do
      process <- readIORef $ ctxServerHandle context
      case process of
        Just handle -> terminateProcess handle
        Nothing -> return ()
    nothingToWatch = do
      files <- readIORef $ ctxFilesToWatch context
      if null files
        then return True
        else do
          waitForTwitch files
          return False
Henrik Tramberend's avatar
Henrik Tramberend committed
206

207
watchFiles = setFilesToWatch
Henrik Tramberend's avatar
Henrik Tramberend committed
208 209 210

-- | Actively waits for the first change to any member in the set of specified
-- | files and their parent directories, then returns.
211 212 213 214 215 216 217 218 219 220 221 222 223
waitForTwitch files = do
  startTime <- getCurrentTime
  let dirs = map takeDirectory files
  let filesAndDirs = Set.toList . Set.fromList $ files ++ dirs
  whileM_ (noModificationSince startTime filesAndDirs) (threadDelay 300000)
  where
    noModificationSince startTime pathes = do
      modified <- mapM (modifiedSince startTime) pathes
      return $ not (or modified)
    modifiedSince time path =
      handle (\(SomeException _) -> return False) $
      do modTime <- getModificationTime path
         return $ diffUTCTime modTime time > 0
Henrik Tramberend's avatar
Henrik Tramberend committed
224 225

-- | Monadic version of list concatenation.
226 227 228
(<++>)
  :: Monad m
  => m [a] -> m [a] -> m [a]
229
(<++>) = liftM2 (++)
Henrik Tramberend's avatar
Henrik Tramberend committed
230 231 232

-- | Mark files as need and return them
markNeeded :: [FilePath] -> Action [FilePath]
233 234 235
markNeeded files = do
  need files
  return files
Henrik Tramberend's avatar
Henrik Tramberend committed
236 237 238 239 240

-- | Removes the last suffix from a filename
dropSuffix s t = fromMaybe t (stripSuffix s t)

-- | Monadic version of suffix replacement for easy binding.
241
replaceSuffixWith :: String -> String -> [FilePath] -> Action [FilePath]
242
replaceSuffixWith suffix with pathes =
Henrik Tramberend's avatar
Henrik Tramberend committed
243 244
  return [dropSuffix suffix d ++ with | d <- pathes]

245
-- | Monadic version of suffix replacement for easy binding.
246
calcTargetPath :: FilePath -> String -> String -> [FilePath] -> Action [FilePath]
247 248 249 250
calcTargetPath projectDir suffix with pathes =
  return [projectDir </> dropSuffix suffix d ++ with | d <- pathes]

-- | Generates an index.md file with links to all generated files of interest.
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
writeIndex out baseUrl decks handouts pages = do
  let decksLinks = map (makeRelative baseUrl) decks
  let handoutsLinks = map (makeRelative baseUrl) handouts
  let pagesLinks = map (makeRelative baseUrl) pages
  projectDir <- getProjectDir
  liftIO $
    writeFile out $
    unlines
      [ "---"
      , "title: Generated Index"
      , "subtitle: " ++ projectDir
      , "---"
      , "# Slide decks"
      , unlines $ map makeLink $ sort decksLinks
      , "# Handouts"
      , unlines $ map makeLink $ sort handoutsLinks
      , "# Supporting Documents"
      , unlines $ map makeLink $ sort pagesLinks
      ]
  where
    makeLink path = "-    [" ++ takeFileName path ++ "](" ++ path ++ ")"

readMetaDataForDir :: FilePath -> Action Y.Value
274 275 276
readMetaDataForDir dir = walkUpTo dir
  where
    walkUpTo dir = do
277 278 279 280 281 282 283
      projectDir <- getProjectDir
      if equalFilePath projectDir dir
        then collectMeta dir
        else do
          fromAbove <- walkUpTo (takeDirectory dir)
          fromHere <- collectMeta dir
          return $ joinMeta fromHere fromAbove
284 285
    --
    collectMeta dir = do
286 287 288 289
      files <- liftIO $ globDir1 (compile "*-meta.yaml") dir
      need files
      meta <- mapM decodeYaml files
      return $ foldl joinMeta (Y.object []) meta
290 291 292 293 294
    --
    joinMeta (Y.Object old) (Y.Object new) = Y.Object (H.union new old)
    joinMeta _ _ = throw $ YamlException "Can only join YAML objects."
    --
    decodeYaml yamlFile = do
295 296 297 298 299 300 301
      result <- liftIO $ Y.decodeFileEither yamlFile
      case result of
        Right object@(Y.Object _) -> return object
        Right _ ->
          throw $
          YamlException $ "Top-level meta value must be an object: " ++ dir
        Left exception -> throw exception
Henrik Tramberend's avatar
Henrik Tramberend committed
302

Henrik Tramberend's avatar
Henrik Tramberend committed
303 304 305
-- | Decodes an array of YAML files and combines the data into one object.
-- Key value pairs from later files overwrite those from early ones.
readMetaDataIO :: [FilePath] -> IO Y.Value
306
readMetaDataIO files =
Henrik Tramberend's avatar
Henrik Tramberend committed
307
  mapM decode files >>= foldM combine (Y.Object HashMap.empty)
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
  where
    decode file = do
      result <- Y.decodeFileEither file
      return (file, result)
    combine (Y.Object obj) (file, Right (Y.Object new)) =
      return (Y.Object (HashMap.union new obj))
    combine obj (file, Right _) = do
      _ <-
        throw $
        YamlException $ file ++ ": top level metadata is not a YAML object."
      return obj
    combine obj (file, Left err) = do
      _ <-
        throw $ YamlException $ file ++ ": " ++ Y.prettyPrintParseException err
      return obj
Henrik Tramberend's avatar
Henrik Tramberend committed
323

324 325 326
-- | TODO This has to be restructured. Metadata files need to be calculated from
-- the source directory and need should be called implicitly.
readMetaData :: [FilePath] -> Action MetaData
327 328 329
readMetaData files = do
  need files
  liftIO $ readMetaDataIO files
Henrik Tramberend's avatar
Henrik Tramberend committed
330

331 332 333 334 335 336
-- | Fixes pandoc escaped # markup in mustache template {{}} markup.
fixMustacheMarkup :: B.ByteString -> T.Text
fixMustacheMarkup content = fixMustacheMarkupText $ E.decodeUtf8 content

-- | Fixes pandoc escaped # markup in mustache template {{}} markup.
fixMustacheMarkupText :: T.Text -> T.Text
337 338 339 340 341 342
fixMustacheMarkupText content =
  T.replace
    (T.pack "{{\\#")
    (T.pack "{{#")
    (T.replace (T.pack "{{\\^") (T.pack "{{^") content)

Henrik Tramberend's avatar
Henrik Tramberend committed
343
-- | Substitutes meta data values in the provided file.
344 345 346 347 348 349 350 351
substituteMetaData :: FilePath -> MT.Value -> IO T.Text
substituteMetaData source metaData = do
  contents <- B.readFile source
  let fixed = fixMustacheMarkup contents
  let result = M.compileTemplate source fixed
  case result of
    Right template -> return $ M.substituteValue template metaData
    Left err -> throw $ MustacheException (show err)
Henrik Tramberend's avatar
Henrik Tramberend committed
352

353
getRelativeSupportDir :: FilePath -> Action FilePath
354 355 356 357 358 359
getRelativeSupportDir from = do
  supportDir <- getSupportDir
  publicDir <- getPublicDir
  return $
    invertPath (makeRelative publicDir (takeDirectory from)) </>
    makeRelative publicDir supportDir
Henrik Tramberend's avatar
Henrik Tramberend committed
360 361

invertPath :: FilePath -> FilePath
362
invertPath fp = joinPath $ map (const "..") $ filter ("." /=) $ splitPath fp
Henrik Tramberend's avatar
Henrik Tramberend committed
363 364

-- | Write a markdown file to a HTML file using the page template.
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
markdownToHtmlDeck :: FilePath -> FilePath -> Action ()
markdownToHtmlDeck markdownFile out = do
  supportDir <- getRelativeSupportDir out
  let options =
        pandocWriterOpts
        { writerStandalone = True
        , writerTemplate = deckTemplate
        , writerHighlight = True
        , writerHighlightStyle = pygments
        , writerHTMLMathMethod =
          MathJax
            "https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"
        -- ,writerHTMLMathMethod =
        --    KaTeX (supportDir </> "katex-0.6.0/katex.min.js")
        --          (supportDir </> "katex-0.6.0/katex.min.css")
        , writerVariables =
          [ ("revealjs-url", supportDir </> "reveal.js")
          , ("decker-support-dir", supportDir)
          ]
        , writerCiteMethod = Citeproc
        }
  pandoc <- readAndPreprocessMarkdown markdownFile
  processed <- processPandocDeck "revealjs" pandoc
  writePandocString "revealjs" options out processed
389

Henrik Tramberend's avatar
Henrik Tramberend committed
390 391 392 393 394 395 396 397 398 399 400 401
type MetaData = Y.Value

-- | Selects a matching pandoc string writer for the format string, or throws an
-- exception.
getPandocWriter :: String -> StringWriter
getPandocWriter format =
  case getWriter format of
    Right (PureStringWriter w) -> w
    Left e -> throw $ PandocException e
    _ -> throw $ PandocException $ "No writer for format: " ++ format

-- | Reads a markdownfile, expands the included files, and substitutes mustache
402 403
-- template variables and calls need.
readAndPreprocessMarkdown :: FilePath -> Action Pandoc
404 405 406 407 408
readAndPreprocessMarkdown markdownFile = do
  projectDir <- getProjectDir
  let baseDir = takeDirectory markdownFile
  readMetaMarkdown markdownFile >>= processIncludes projectDir baseDir >>=
    populateCache
Henrik Tramberend's avatar
Henrik Tramberend committed
409 410

populateCache :: Pandoc -> Action Pandoc
411 412 413
populateCache pandoc = do
  cacheDir <- getCacheDir
  liftIO $ walkM (cacheRemoteImages cacheDir) pandoc
Henrik Tramberend's avatar
Henrik Tramberend committed
414

Henrik Tramberend's avatar
Henrik Tramberend committed
415
-- | Write a markdown file to a HTML file using the page template.
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
markdownToHtmlPage :: FilePath -> FilePath -> Action ()
markdownToHtmlPage markdownFile out = do
  supportDir <- getRelativeSupportDir out
  let options =
        pandocWriterOpts
        { writerHtml5 = True
        , writerStandalone = True
        , writerTemplate = pageTemplate
        , writerHighlight = True
        , writerHighlightStyle = pygments
        , writerHTMLMathMethod =
          MathJax
            "https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"
        -- ,writerHTMLMathMethod =
        --    KaTeX (supportDir </> "katex-0.6.0/katex.min.js")
        --          (supportDir </> "katex-0.6.0/katex.min.css")
        , writerVariables = [("decker-support-dir", supportDir)]
        , writerCiteMethod = Citeproc
        }
  pandoc <- readAndPreprocessMarkdown markdownFile
  processed <- processPandocPage "html5" pandoc
  writePandocString "html5" options out processed
Henrik Tramberend's avatar
Henrik Tramberend committed
438 439

-- | Write a markdown file to a PDF file using the handout template.
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
markdownToPdfPage :: FilePath -> FilePath -> Action ()
markdownToPdfPage markdownFile out = do
  let options =
        pandocWriterOpts
        { writerStandalone = True
        , writerTemplate = pageLatexTemplate
        , writerHighlight = True
        , writerHighlightStyle = pygments
        , writerCiteMethod = Citeproc
        }
  pandoc <- readAndPreprocessMarkdown markdownFile
  processed <- processPandocPage "latex" pandoc
  putNormal $ "# pandoc (for " ++ out ++ ")"
  pandocMakePdf options processed out

pandocMakePdf options processed out = do
  result <- liftIO $ makePDF "pdflatex" writeLaTeX options processed
  case result of
    Left err -> throw $ PandocException (show err)
    Right pdf -> liftIO $ LB.writeFile out pdf
Henrik Tramberend's avatar
Henrik Tramberend committed
460 461

-- | Write a markdown file to a HTML file using the handout template.
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
markdownToHtmlHandout :: FilePath -> FilePath -> Action ()
markdownToHtmlHandout markdownFile out = do
  pandoc <- readAndPreprocessMarkdown markdownFile
  processed <- processPandocHandout "html" pandoc
  supportDir <- getRelativeSupportDir out
  let options =
        pandocWriterOpts
        { writerHtml5 = True
        , writerStandalone = True
        , writerTemplate = handoutTemplate
        , writerHighlight = True
        , writerHighlightStyle = pygments
        , writerHTMLMathMethod =
          MathJax
            "https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"
        -- ,writerHTMLMathMethod =
        --    KaTeX (supportDir </> "katex-0.6.0/katex.min.js")
        --          (supportDir </> "katex-0.6.0/katex.min.css")
        , writerVariables = [("decker-support-dir", supportDir)]
        , writerCiteMethod = Citeproc
        }
  writePandocString "html5" options out processed
Henrik Tramberend's avatar
Henrik Tramberend committed
484 485

-- | Write a markdown file to a PDF file using the handout template.
486
markdownToPdfHandout :: FilePath -> FilePath -> Action ()
487
markdownToPdfHandout markdownFile out = do
488 489 490 491 492 493 494 495 496 497 498 499
  pandoc <- readAndPreprocessMarkdown markdownFile
  processed <- processPandocHandout "latex" pandoc
  let options =
        pandocWriterOpts
        { writerStandalone = True
        , writerTemplate = handoutLatexTemplate
        , writerHighlight = True
        , writerHighlightStyle = pygments
        , writerCiteMethod = Citeproc
        }
  putNormal $ "# pandoc (for " ++ out ++ ")"
  pandocMakePdf options processed out
500 501

readMetaMarkdown :: FilePath -> Action Pandoc
502 503 504 505 506 507
readMetaMarkdown markdownFile = do
  need [markdownFile]
  metaData <- readMetaDataForDir (takeDirectory markdownFile)
  pandoc <- liftIO $ readMetaMarkdownIO markdownFile metaData
  projectDir <- getProjectDir
  return $ walk (adjustImageUrls projectDir (takeDirectory markdownFile)) pandoc
508

509 510 511 512 513 514 515 516
-- Remove automatic identifier creation for headers. It does not work well with
-- the current include mechanism, if slides have duplicate titles in separate
-- include files.
deckerPandocExtensions :: Set.Set Extension
deckerPandocExtensions = Set.delete Ext_auto_identifiers pandocExtensions

pandocReaderOpts :: ReaderOptions
pandocReaderOpts =
517 518 519
  def
  { readerExtensions = deckerPandocExtensions
  }
520 521 522

pandocWriterOpts :: WriterOptions
pandocWriterOpts =
523 524 525
  def
  { writerExtensions = deckerPandocExtensions
  }
526 527

readMetaMarkdownIO :: FilePath -> Y.Value -> IO Pandoc
528 529 530 531 532
readMetaMarkdownIO markdownFile metaData = do
  text <- substituteMetaData markdownFile (MT.mFromJSON metaData)
  case readMarkdown pandocReaderOpts $ T.unpack text of
    Right pandoc -> return pandoc
    Left err -> throw $ PandocException (show err)
Henrik Tramberend's avatar
Henrik Tramberend committed
533

534 535 536 537 538 539 540 541 542
isLocalURI :: String -> Bool
isLocalURI url = isNothing $ parseURI url

isRemoteURI :: String -> Bool
isRemoteURI = not . isLocalURI

isCacheableURI :: String -> Bool
isCacheableURI url =
  case parseURI url of
543
    Just uri -> uriScheme uri `elem` ["http:", "https:"]
544 545 546 547 548 549 550
    Nothing -> False

-- | Walks over all images in a Pandoc document and transforms image URLs like
-- this: 1. Remote URLs are not transformed. 2. Absolute URLs are intepreted
-- relative to the project root directory. 3. Relative URLs are intepreted
-- relative to the containing document.
adjustImageUrls :: FilePath -> FilePath -> Pandoc -> Pandoc
551
adjustImageUrls projectDir baseDir = walk adjustBlock . walk adjustInline
552
  where
553 554
    adjustInline (Image attr inlines (url, title)) =
      Image attr inlines (adjustLocalUrl projectDir baseDir url, title)
555 556
    adjustInline other = other
    adjustBlock (Header 1 attr inlines) =
557
      Header 1 (adjustBgImageUrl attr) inlines
558
    adjustBlock other = other
559 560 561 562 563 564 565 566 567
    adjustBgImageUrl (i, cs, kvs) =
      ( i
      , cs
      , map
          (\(k, v) ->
              if k == "data-background-image"
                then (k, adjustLocalUrl projectDir baseDir v)
                else (k, v))
          kvs)
568 569 570 571

adjustLocalUrl :: FilePath -> FilePath -> FilePath -> FilePath
adjustLocalUrl root base url
  | isLocalURI url =
572 573 574
    if isAbsolute url
      then root </> makeRelative "/" url
      else base </> url
575 576
adjustLocalUrl _ _ url = url

Henrik Tramberend's avatar
Henrik Tramberend committed
577 578 579 580 581 582 583
-- cacheRemoteImages :: FilePath -> [FilePath] -> [FilePath] -> Action ()
-- cacheRemoteImages cacheDir metaFiles markdownFiles =
--   do mapM_ cacheImages markdownFiles
--   where cacheImages markdownFile =
--           do pandoc <- readMetaMarkdown markdownFile
--              _ <- liftIO $ walkM (cachePandocImages cacheDir) pandoc
--              putNormal $ "# pandoc (cached images for " ++ markdownFile ++ ")"
Henrik Tramberend's avatar
Henrik Tramberend committed
584
-- Transitively splices all include files into the pandoc document.
585
processIncludes :: FilePath -> FilePath -> Pandoc -> Action Pandoc
586
processIncludes rootDir baseDir (Pandoc meta blocks) = do
587 588
  included <- processBlocks baseDir blocks
  return $ Pandoc meta included
589 590 591
  where
    processBlocks :: FilePath -> [Block] -> Action [Block]
    processBlocks base blcks = do
592 593
      spliced <- foldM (include base) [] blcks
      return $ concat $ reverse spliced
594
    include :: FilePath -> [[Block]] -> Block -> Action [[Block]]
595 596 597 598 599
    include base result (Para [Link _ [Str "#include"] (url, _)]) = do
      let filePath = adjustLocalUrl rootDir base url
      Pandoc _ b <- readMetaMarkdown filePath
      included <- processBlocks (takeDirectory filePath) b
      return $ included : result
600
    include _ result block = return $ [block] : result
601

Henrik Tramberend's avatar
Henrik Tramberend committed
602
cacheRemoteImages :: FilePath -> Pandoc -> IO Pandoc
603
cacheRemoteImages cacheDir = walkM cacheRemoteImage
604
  where
605 606 607
    cacheRemoteImage (Image attr inlines (url, title)) = do
      cachedFile <- cacheRemoteFile cacheDir url
      return (Image attr inlines (cachedFile, title))
608
    cacheRemoteImage img = return img
Henrik Tramberend's avatar
Henrik Tramberend committed
609 610 611

cacheRemoteFile :: FilePath -> String -> IO FilePath
cacheRemoteFile cacheDir url
612
  | isCacheableURI url = do
613 614 615 616 617 618 619 620 621 622 623 624
    let cacheFile = cacheDir </> hashURI url
    exists <- Dir.doesFileExist cacheFile
    if exists
      then return cacheFile
      else catch
             (do content <- downloadUrl url
                 createDirectoryIfMissing True cacheDir
                 LB.writeFile cacheFile content
                 return cacheFile)
             (\e -> do
                putStrLn $ "Warning: " ++ show (e :: SomeException)
                return url)
Henrik Tramberend's avatar
Henrik Tramberend committed
625 626 627 628
cacheRemoteFile _ url = return url

clearCachedFile :: FilePath -> String -> IO ()
clearCachedFile cacheDir url
629
  | isCacheableURI url = do
630 631 632
    let cacheFile = cacheDir </> hashURI url
    exists <- Dir.doesFileExist cacheFile
    when exists $ removeFile cacheFile
Henrik Tramberend's avatar
Henrik Tramberend committed
633 634 635
clearCachedFile _ _ = return ()

downloadUrl :: String -> IO LB.ByteString
636
downloadUrl url = do
637 638 639 640 641 642 643 644 645 646 647 648
  request <- parseRequest url
  result <- httpLBS request
  let status = getResponseStatus result
  if status == ok200
    then return $ getResponseBody result
    else throw $
         HttpException $
         "Cannot download " ++
         url ++
         " (" ++
         show (statusCode status) ++
         " " ++ B.unpack (statusMessage status) ++ ")"
Henrik Tramberend's avatar
Henrik Tramberend committed
649 650

hashURI :: String -> String
651
hashURI uri = show (md5 $ L8.pack uri) SF.<.> SF.takeExtension uri
Henrik Tramberend's avatar
Henrik Tramberend committed
652

653
processPandocPage :: String -> Pandoc -> Action Pandoc
654
processPandocPage format pandoc = do
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
  let f = Just (Format format)
  -- processed <- liftIO $ processCites' pandoc >>= walkM (useCachedImages
  -- cacheDir)
  cacheDir <- getCacheDir
  processed <- liftIO $ walkM (useCachedImages cacheDir) pandoc
  return $ expandMacros f processed

processPandocDeck :: String -> Pandoc -> Action Pandoc
processPandocDeck format pandoc = do
  let f = Just (Format format)
  -- processed <- liftIO $ processCites' pandoc >>= walkM (useCachedImages
  -- cacheDir)
  cacheDir <- getCacheDir
  processed <- liftIO $ walkM (useCachedImages cacheDir) pandoc
  return $ (makeSlides f . expandMacros f) processed

processPandocHandout :: String -> Pandoc -> Action Pandoc
processPandocHandout format pandoc = do
  let f = Just (Format format)
  -- processed <- liftIO $ processCites' pandoc >>= walkM (useCachedImages
  -- cacheDir)
  cacheDir <- getCacheDir
  processed <- liftIO $ walkM (useCachedImages cacheDir) pandoc
  return $ (expandMacros f . filterNotes f) processed
Henrik Tramberend's avatar
Henrik Tramberend committed
679 680 681

type StringWriter = WriterOptions -> Pandoc -> String

682
writePandocString :: String -> WriterOptions -> FilePath -> Pandoc -> Action ()
683 684 685 686 687
writePandocString format options out pandoc = do
  let writer = getPandocWriter format
  final <- copyImages (takeDirectory out) pandoc
  writeFile' out (writer options final)
  putNormal $ "# pandoc for (" ++ out ++ ")"
Henrik Tramberend's avatar
Henrik Tramberend committed
688

Henrik Tramberend's avatar
Henrik Tramberend committed
689
copyImages :: FilePath -> Pandoc -> Action Pandoc
690
copyImages baseDir pandoc = do
691 692 693 694
  projectDir <- getProjectDir
  publicDir <- getPublicDir
  walkM (copyAndLinkInline projectDir publicDir) pandoc >>=
    walkM (copyAndLinkBlock projectDir publicDir)
695
  where
696 697 698
    copyAndLinkInline project public (Image attr inlines (url, title)) = do
      relUrl <- copyAndLinkFile project public baseDir url
      return (Image attr inlines (relUrl, title))
699 700
    copyAndLinkInline _ _ inline = return inline
    copyAndLinkBlock project public (Header 1 attr inlines) = do
701 702
      relAttr <- copyBgImageUrl project public attr
      return (Header 1 relAttr inlines)
703
    copyAndLinkBlock _ _ block = return block
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
    copyBgImageUrl project public (i, cs, kvs) = do
      relKvs <-
        mapM
          (\(k, v) ->
              if k == "data-background-image"
                then do
                  relUrl <- copyAndLinkFile project public baseDir v
                  return (k, relUrl)
                else return (k, v))
          kvs
      return (i, cs, relKvs)

copyAndLinkFile :: FilePath
                -> FilePath
                -> FilePath
                -> FilePath
                -> Action FilePath
721
copyAndLinkFile project public base url = do
722 723 724 725 726 727 728 729 730 731 732
  let rel = makeRelative project url
  if rel == url
    then return url
    else do
      let pub = public </> rel
      liftIO $ createDirectoryIfMissing True (takeDirectory pub)
      copyFileChanged url pub
      return $ traceId $ makeRelativeTo (traceId base) (traceId pub)

-- | Express the second path argument as relative to the first. 
-- Both arguments are expected to be absolute pathes. 
Henrik Tramberend's avatar
Henrik Tramberend committed
733 734
makeRelativeTo :: FilePath -> FilePath -> FilePath
makeRelativeTo dir file =
735 736 737 738 739 740 741 742
  let (d, f) = removeCommonPrefix (splitDirectories dir) (splitDirectories file)
  in normalise $ invertPath (joinPath d) </> joinPath f

removeCommonPrefix :: [FilePath] -> [FilePath] -> ([FilePath], [FilePath])
removeCommonPrefix al@(a:as) bl@(b:bs)
  | a == b = removeCommonPrefix as bs
  | otherwise = (al, bl)
removeCommonPrefix [] b = ([], b)
Henrik Tramberend's avatar
Henrik Tramberend committed
743

Henrik Tramberend's avatar
Henrik Tramberend committed
744
writeExampleProject :: Action ()
745
writeExampleProject = mapM_ writeOne deckerExampleDir
746
  where
747 748 749 750 751 752
    writeOne (path, contents) = do
      exists <- Development.Shake.doesFileExist path
      unless exists $
        do liftIO $ createDirectoryIfMissing True (takeDirectory path)
           liftIO $ B.writeFile path contents
           putNormal $ "# create (for " ++ path ++ ")"
Henrik Tramberend's avatar
Henrik Tramberend committed
753

754
writeEmbeddedFiles :: [(FilePath, B.ByteString)] -> FilePath -> Action ()
755
writeEmbeddedFiles files dir = do
756 757
  let absolute = map (\(path, contents) -> (dir </> path, contents)) files
  mapM_ write absolute
758
  where
759 760 761 762
    write (path, contents) = do
      liftIO $ Dir.createDirectoryIfMissing True (takeDirectory path)
      exists <- liftIO $ Dir.doesFileExist path
      unless exists $ liftIO $ B.writeFile path contents
763

Henrik Tramberend's avatar
Henrik Tramberend committed
764
lookupValue :: String -> Y.Value -> Maybe Y.Value
765
lookupValue key (Y.Object hashTable) = HashMap.lookup (T.pack key) hashTable
Henrik Tramberend's avatar
Henrik Tramberend committed
766 767
lookupValue key _ = Nothing

768
metaValueAsString :: String -> Y.Value -> Maybe String
Henrik Tramberend's avatar
Henrik Tramberend committed
769
metaValueAsString key meta =
770 771 772
  case splitOn "." key of
    [] -> Nothing
    k:ks -> lookup' ks (lookupValue k meta)
773 774 775 776 777 778 779
  where
    lookup' :: [String] -> Maybe Y.Value -> Maybe String
    lookup' [] (Just (Y.String text)) = Just (T.unpack text)
    lookup' [] (Just (Y.Number n)) = Just (show n)
    lookup' [] (Just (Y.Bool b)) = Just (show b)
    lookup' (k:ks) (Just obj@(Y.Object _)) = lookup' ks (lookupValue k obj)
    lookup' _ _ = Nothing
Henrik Tramberend's avatar
Henrik Tramberend committed
780 781 782

-- | Tool specific exceptions
data DeckerException
783 784 785 786 787 788 789
  = MustacheException String
  | PandocException String
  | YamlException String
  | HttpException String
  | RsyncUrlException
  | DecktapeException String
  deriving (Typeable)
Henrik Tramberend's avatar
Henrik Tramberend committed
790 791 792 793

instance Exception DeckerException

instance Show DeckerException where
794 795 796 797 798 799 800
  show (MustacheException e) = e
  show (HttpException e) = e
  show (PandocException e) = e
  show (YamlException e) = e
  show (DecktapeException e) = "decktape.sh failed for reason: " ++ e
  show RsyncUrlException =
    "attributes 'destinationRsyncHost' or 'destinationRsyncPath' not defined in meta data"