1
1
mirror of https://github.com/sol/hpack.git synced 2024-10-04 03:38:00 +03:00

Add 'hpackSilent', with result datatype

This commit is contained in:
Michael Sloan 2016-05-03 23:55:57 -07:00
parent 8d9d9cb319
commit 25e31f20f7

View File

@ -1,6 +1,9 @@
{-# LANGUAGE CPP #-}
module Hpack (
hpack
, hpackSilent
, Result(..)
, Status(..)
, version
, main
#ifdef TEST
@ -86,27 +89,46 @@ parseVersion xs = case [v | (v, "") <- readP_to_S Version.parseVersion xs] of
hpack :: FilePath -> Bool -> IO ()
hpack = hpackWithVersion version
hpackSilent :: FilePath -> IO Result
hpackSilent = hpackWithVersionSilent version
data Result = Result {
resultWarnings :: [String]
, resultCabalFile :: String
, resultStatus :: Status
}
data Status = Generated | AlreadyGeneratedByNewerHpack | OutputUnchanged
hpackWithVersion :: Version -> FilePath -> Bool -> IO ()
hpackWithVersion v dir verbose = do
(warnings, name, new) <- run dir
forM_ warnings $ \warning -> hPutStrLn stderr ("WARNING: " ++ warning)
r <- hpackWithVersionSilent v dir
forM_ (resultWarnings r) $ \warning -> hPutStrLn stderr ("WARNING: " ++ warning)
when verbose $ putStrLn $
case resultStatus r of
Generated -> "generated " ++ resultCabalFile r
OutputUnchanged -> resultCabalFile r ++ " is up-to-date"
AlreadyGeneratedByNewerHpack -> resultCabalFile r ++ " was generated with a newer version of hpack, please upgrade and try again."
old <- either (const Nothing) (Just . splitHeader) <$> tryJust (guard . isDoesNotExistError) (readFile name >>= (return $!!))
hpackWithVersionSilent :: Version -> FilePath -> IO Result
hpackWithVersionSilent v dir = do
(warnings, cabalFile, new) <- run dir
old <- either (const Nothing) (Just . splitHeader) <$> tryJust (guard . isDoesNotExistError) (readFile cabalFile >>= (return $!!))
let oldVersion = fmap fst old >>= extractVersion
if (oldVersion <= Just v) then do
if (fmap snd old == Just (lines new)) then do
output (name ++ " is up-to-date")
else do
(writeFile name $ header v ++ new)
output ("generated " ++ name)
else do
output (name ++ " was generated with a newer version of hpack, please upgrade and try again.")
status <-
if (oldVersion <= Just v) then
if (fmap snd old == Just (lines new)) then
return OutputUnchanged
else do
writeFile cabalFile $ header v ++ new
return Generated
else
return AlreadyGeneratedByNewerHpack
return Result
{ resultWarnings = warnings
, resultCabalFile = cabalFile
, resultStatus = status
}
where
splitHeader :: String -> ([String], [String])
splitHeader = fmap (dropWhile null) . span ("--" `isPrefixOf`) . lines
output :: String -> IO ()
output message
| verbose = putStrLn message
| otherwise = return ()