{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveFunctor #-}
module Parse
( parsePackageDescription
, readPackageDescription
, displayError
, printWarnings
, Result(..)
, result
)
where
import Control.DeepSeq
import Control.Monad.Compat
import Data.Data
import Data.Maybe
import Distribution.PackageDescription
import Distribution.PackageDescription.Parsec
( parseGenericPackageDescription
, runParseResult
)
import Distribution.Parsec.Common
import Distribution.Simple.Utils
import Distribution.Verbosity
import Distribution.Version
import GHC.Generics
import Prelude.Compat
import System.Exit
import Data.Functor.Classes
data Result a
= Error [PError]
| Warn [PWarning]
| Success a
deriving (Show, Eq, Functor, Generic, Typeable, Data, Generic1)
instance Show1 Result where
liftShowsPrec sp _ p (Success n ) = showsUnaryWith sp "Success" p n
liftShowsPrec _ _ p (Warn pws) = showsUnaryWith showsPrec "Warn" p pws
liftShowsPrec _ _ p (Error s ) = showsUnaryWith showsPrec "Error" p s
instance Eq1 Result where
liftEq eq (Success a ) (Success b ) = eq a b
liftEq _ (Error s ) (Error s2 ) = s == s2
liftEq _ (Warn pws) (Warn pws2) = pws == pws2
liftEq _ _ _ = False
result :: ([PError] -> b) -> ([PWarning] -> b) -> (a -> b) -> Result a -> b
result e w s p = case p of
Error l -> e l
Warn ws -> w ws
Success r -> s r
deriving instance Data PError
deriving instance Eq PError
deriving instance Eq PWarning
instance NFData a => NFData (Result a)
deriving instance Data PWarning
deriving instance Data Position
deriving instance Data PWarnType
deriving instance Typeable PWarning
parsePackageDescription input =
let (warnings, r) = runParseResult $ parseGenericPackageDescription input
in case r of
Left (_, errors) -> Error errors
Right x | null warnings -> parseResult x
| otherwise -> Warn warnings
where
parseResult gpd =
if specVersionRaw (packageDescription gpd) == Right anyVersion
then Warn [PWarning PWTOther zeroPos versWarning]
else Success gpd
versWarning
= "File does not specify a cabal-version. stylish-cabal requires at least 1.2"
readPackageDescription fpath =
result (displayError fpath) (printWarnings fpath) return
. parsePackageDescription
printWarnings :: Maybe FilePath -> [PWarning] -> IO a
printWarnings fpath ps =
mapM_ (warn normal . showPWarning (fromMaybe "<input>" fpath)) ps
>> exitFailure
displayError :: Maybe FilePath -> [PError] -> IO a
displayError fpath warns =
mapM_ (warn normal . showPError (fromMaybe "<input>" fpath)) warns
>> exitFailure