module HolyProject.GitConfig
( getNameAndMailFromGitConfig
)
where
import qualified Data.ByteString.Lazy.Char8 as LZ
import Control.Monad (guard)
import Control.Exception
import System.IO.Error
import System.Environment (getEnv)
getNameAndMailFromGitConfig :: IO (Maybe String, Maybe String)
getNameAndMailFromGitConfig = return . getNameAndMail =<< safeReadGitConfig
safeReadGitConfig :: IO LZ.ByteString
safeReadGitConfig = do
e <- tryJust (guard . isDoesNotExistError)
(do
home <- getEnv "HOME"
LZ.readFile $ home ++ "/.gitconfig" )
return $ either (const LZ.empty) id e
getNameAndMail :: LZ.ByteString -> (Maybe String,Maybe String)
getNameAndMail gitConfigContent = (getFirstValueFor splitted "name",
getFirstValueFor splitted "email")
where
splitted :: [[LZ.ByteString]]
splitted = map LZ.words (LZ.lines gitConfigContent)
getFirstValueFor :: [[LZ.ByteString]] -> String -> Maybe String
getFirstValueFor splitted keyname = firstJust (map (getValueForKey keyname) splitted)
firstJust :: (Eq a) => [Maybe a] -> Maybe a
firstJust l = case dropWhile (==Nothing) l of
[] -> Nothing
(j:_) -> j
getValueForKey :: String
-> [LZ.ByteString]
-> Maybe String
getValueForKey el (n:e:xs) = if (n == LZ.pack el) && (e == LZ.pack "=")
then Just (LZ.unpack (LZ.unwords xs))
else Nothing
getValueForKey _ _ = Nothing