avoid partial functions, and added check for correct sha content

This commit is contained in:
Joey Hess 2011-12-15 15:57:47 -04:00
parent e7a555bf21
commit 111b6937ec

View file

@ -10,17 +10,26 @@ module Git.Sha where
import Common import Common
import Git.Types import Git.Types
{- Runs an action that causes a git subcommand to emit a sha, and strips {- Runs an action that causes a git subcommand to emit a Sha, and strips
any trailing newline, returning the sha. -} any trailing newline, returning the sha. -}
getSha :: String -> IO String -> IO Sha getSha :: String -> IO String -> IO Sha
getSha subcommand a = do getSha subcommand a = maybe bad return =<< extractSha <$> a
t <- a where
let t' = if last t == '\n' bad = error $ "failed to read sha from git " ++ subcommand
then init t
else t {- Extracts the Sha from a string. There can be a trailing newline after
when (length t' /= shaSize) $ - it, but nothing else. -}
error $ "failed to read sha from git " ++ subcommand ++ " (" ++ t' ++ ")" extractSha :: String -> Maybe Sha
return $ Ref t' extractSha s
| len == shaSize = val s
| len == shaSize + 1 && length s' == shaSize = val s'
| otherwise = Nothing
where
len = length s
s' = firstLine s
val v
| all (`elem` "1234567890ABCDEFabcdef") v = Just $ Ref v
| otherwise = Nothing
{- Size of a git sha. -} {- Size of a git sha. -}
shaSize :: Int shaSize :: Int