summaryrefslogtreecommitdiff
path: root/hs/Links.hs
blob: cb8fd271a866d79f1438ddcf899828b6f8617c16 (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
{-# LANGUAGE OverloadedStrings
           , ImportQualifiedPost
           #-}

module Links
( extractLinks
, findLinks
, buildBacklinkSet
) where

import Control.Monad.IO.Class (liftIO)

import Data.Default (def)

import Data.Map qualified as M

import Data.Set (Set)
import Data.Set qualified as S

import Data.Text (Text)
import Data.Text.IO qualified as T

import System.FilePath (joinPath, (</>))

import Text.Pandoc (PandocIO, readVimwiki)
import Text.Pandoc.Definition (Pandoc, Inline (Link))
import Text.Pandoc.Walk (query)


-- Find all wikilinks in the given document
extractLinks :: Pandoc -> [Text]
extractLinks = query extractLink
  where extractLink :: Inline -> [Text]
        extractLink (Link _ _ (target, "wikilink")) = [target]
        extractLink _ = []


findLinks :: FilePath -> [FilePath] -> PandocIO (FilePath, [Text])
findLinks wiki_root parts = do
    let item_path = joinPath parts
    let inTarget  = wiki_root </> item_path
    text <- liftIO $ T.readFile inTarget

    pandoc <- readVimwiki def text

    return (item_path, extractLinks pandoc)

    -- let htmlString = toStrict . renderHtml $ html
    -- liftIO $ T.writeFile outTarget htmlString


buildBacklinkSet :: FilePath -> [Text] -> M.Map Text (Set FilePath)
buildBacklinkSet source targets = foldr (M.alter f) M.empty targets
  where f Nothing    = Just $ S.singleton source
        f (Just lst) = Just $ S.insert source lst