packages feed

casa-reoc-0.1.0.0: src/ReOC/Render/BuildInfo.hs

{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -Wall #-}

{- | The values of the placeholders that the document build fills: the commit
that the documents are built from, where they are published, and the date of
the declaration. The documents keep the placeholders, so that the build
records its own values; 'fillPlaceholders' fills them for documents made
outside the build, such as from GHCi.
-}
module ReOC.Render.BuildInfo (
  BuildInfo (..),
  placeholders,
  fillPlaceholders,
) where

import Data.Text (Text)
import qualified Data.Text as Text
import Data.Time.Calendar (Day)
import ReOC.Render.Text (dayParts, escapeXml)

{- $setup
>>> :set -XOverloadedStrings
>>> import Data.Time.Calendar (fromGregorian)
-}

-- | The values of the placeholders of the document build.
data BuildInfo = BuildInfo
  { buildCommitSha :: Text
  -- ^ @${CI_COMMIT_SHA}@: the commit that the documents are built from
  , buildPagesUrl :: Text
  -- ^ @${CI_PAGES_URL}@: where the documents are published
  , buildDeclarationDate :: Day
  -- ^ @${DECLARATION_DAY}@, @${DECLARATION_MONTH}@ and @${DECLARATION_YEAR}@: the date of the declaration of the application
  }
  deriving (Eq, Ord, Show)

-- | Each placeholder of the document build, with its value, escaped for XML.
placeholders :: BuildInfo -> [(Text, Text)]
placeholders b =
  let (dd, mm, yyyy) = dayParts (buildDeclarationDate b)
   in [ ("${CI_COMMIT_SHA}", escapeXml (buildCommitSha b))
      , ("${CI_PAGES_URL}", escapeXml (buildPagesUrl b))
      , ("${DECLARATION_DAY}", dd)
      , ("${DECLARATION_MONTH}", mm)
      , ("${DECLARATION_YEAR}", yyyy)
      ]

{- | Fills the placeholders of the document build in a document.

>>> fillPlaceholders (BuildInfo "abc123" "https://example.net" (fromGregorian 2026 10 23)) "${CI_COMMIT_SHA} ${DECLARATION_DAY}/${DECLARATION_MONTH}/${DECLARATION_YEAR}"
"abc123 23/10/2026"
-}
fillPlaceholders :: BuildInfo -> Text -> Text
fillPlaceholders b t =
  foldl (\acc (k, v) -> Text.replace k v acc) t (placeholders b)