summaryrefslogtreecommitdiffstats
path: root/src/MdBlocks/Resolver.hs
blob: 1713a16f67f2e0856d10961bb435193cef08253d (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
module MdBlocks.Resolver
  ( ResolveError(..)
  , resolveBlock
  , formatResolveError
  )
where

import Data.List (intercalate)
import qualified Data.Text as T

import MdBlocks.Address
import MdBlocks.Types

data ResolveError
  = BlockNotFound
  | DuplicateBlockId [Block]
  deriving (Show, Eq)

resolveBlock
  :: Address
  -> [Block]
  -> Either ResolveError Block
resolveBlock address blocks =
  case matches of
    [] ->
      Left BlockNotFound

    [block] ->
      Right block

    many ->
      Left (DuplicateBlockId many)
  where
    matches =
      [ b
      | b <- blocks
      , blockFile b == addressFile address
      , mdId (blockMeta b) == Just (addressId address)
      ]

formatResolveError
  :: Address
  -> ResolveError
  -> String
formatResolveError address err =
  case err of
    BlockNotFound ->
      "block not found: "
        ++ showAddress address

    DuplicateBlockId blocks ->
      "duplicate block id '"
        ++ T.unpack (addressId address)
        ++ "' in "
        ++ addressFile address
        ++ "\n  found at "
        ++ formatLines blocks

formatLines :: [Block] -> String
formatLines blocks =
  "lines "
    ++ intercalate ", " (map (show . blockStart) blocks)

showAddress :: Address -> String
showAddress address =
  addressFile address
    ++ "#"
    ++ T.unpack (addressId address)