{-# LANGUAGE BlockArguments #-}
{-|
Module      : KMonad.Args.TH
Description : Template Haskell to use in the CLI
Copyright   : (c) slotThe, 2021
License     : MIT

Maintainer  : soliditsallgood@mailbox.org
Stability   : experimental
Portability : non-portable (TH)

-}
module KMonad.Args.TH (gitHash) where

import KMonad.Prelude

import Language.Haskell.TH (Exp, Q)
import Language.Haskell.TH.Syntax (runIO)
import UnliftIO.Process (readProcessWithExitCode)


-- | Get the git hash of the current revision at compile time
gitHash :: Q Exp
gitHash :: Q Exp
gitHash = do
  [Char]
str <- IO [Char] -> Q [Char]
forall a. IO a -> Q a
runIO do
    (ExitCode
exitCode, [Char]
hash, [Char]
_) <- [Char] -> [[Char]] -> [Char] -> IO (ExitCode, [Char], [Char])
forall (m :: * -> *).
MonadIO m =>
[Char] -> [[Char]] -> [Char] -> m (ExitCode, [Char], [Char])
readProcessWithExitCode [Char]
"git" [[Char]
"rev-parse", [Char]
"HEAD"] [Char]
""
    [Char] -> IO [Char]
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure case ExitCode
exitCode of
      ExitCode
ExitSuccess -> (Char -> Bool) -> [Char] -> [Char]
forall a. (a -> Bool) -> [a] -> [a]
takeWhile (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'\n') [Char]
hash
      ExitCode
_           -> [Char]
""
  [| fromString str |]