packages feed

document-build-0.1.0.0: src/Document/Build/Hash.hs

{-# OPTIONS_GHC -Wall #-}

-- | Commands that compute hashes of files.
module Document.Build.Hash (
  sha256,
  sha256Hex,
) where

import Control.Monad.Trans.Class (lift)
import qualified Crypto.Hash.SHA256 as SHA256
import qualified Data.ByteString as ByteString
import qualified Data.ByteString.Lazy as LazyByteString
import Document.Build.Build (Command, io, requireInput)
import Document.Build.Error (ReviewBuildError)
import Numeric (showHex)

{- $setup
>>> import qualified Data.ByteString.Lazy.Char8 as Char8
-}

{- | The SHA-256 hash of the file being operated on, in lower-case
hexadecimal, as printed by @sha256sum@.

@since 0.1.0.0
-}
sha256 :: (ReviewBuildError e) => Command e String
sha256 =
  do
    i <- requireInput
    lift (io (sha256Hex <$> LazyByteString.readFile i))

{- | The SHA-256 hash of a byte string, in lower-case hexadecimal.

>>> sha256Hex (Char8.pack "abc")
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"

>>> sha256Hex LazyByteString.empty
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"

@since 0.1.0.0
-}
sha256Hex :: LazyByteString.ByteString -> String
sha256Hex =
  ByteString.foldr (\w s -> let h = showHex w s in if w < 16 then '0' : h else h) "" . SHA256.hashlazy