aboutsummaryrefslogtreecommitdiffstats
path: root/app/Issue/Tag.hs
blob: ca550aa8fee02a07756ce380f6ccffe33b585e38 (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
module Issue.Tag
  ( Tag (..),
    extractTags,
    tagKey,
    tagValue,
    tagValuesOf,
  )
where

import CMark qualified as D
import Data.Binary (Binary)
import Data.Maybe (catMaybes, mapMaybe)
import Data.Text (Text)
import Data.Text qualified as T
import GHC.Generics (Generic)

data Tag = Tag Text (Maybe Text) deriving (Show, Generic, Binary, Eq)

tagKey :: Tag -> Text
tagKey (Tag k _) = k

tagValue :: Tag -> Maybe Text
tagValue (Tag _ v) = v

tagValuesOf :: Text -> [Tag] -> [Text]
tagValuesOf key =
  mapMaybe
    ( \tag ->
        if tagKey tag == key
          then tagValue tag
          else Nothing
    )

extractTags :: Text -> [Tag]
extractTags = collect . D.commonmarkToNode []
  where
    collect (D.Node _ (D.CODE _) _) = []
    collect (D.Node _ (D.CODE_BLOCK _ _) _) = []
    collect (D.Node _ (D.TEXT s) ns) = extract s ++ concatMap collect ns
    collect (D.Node _ _ []) = []
    collect (D.Node _ _ ns) = concatMap collect ns

    extract =
      catMaybes
        . map
          ( ( \case
                ((T.uncons -> Just ('@', k)) : v) ->
                  case T.strip (T.unwords v) of
                    "" -> Just (Tag k Nothing)
                    v' -> Just (Tag k (Just v'))
                _ -> Nothing
            )
              . T.words
          )
        . T.lines