module CabalHelper.Compiletime.Sandbox where
import Control.Applicative
import Data.Char
import Data.Maybe
import Data.List
import System.FilePath
import Prelude
import qualified Data.Traversable as T
import CabalHelper.Shared.Common
import CabalHelper.Compiletime.Program.GHC
( GhcVersion (..), showGhcVersion )
getSandboxPkgDb :: String
-> GhcVersion
-> FilePath
-> IO (Maybe FilePath)
getSandboxPkgDb platform ghcVer projdir = do
mConf <-
T.traverse readFile =<< mightExist (projdir </> "cabal.sandbox.config")
return $ fixPkgDbVer <$> (extractSandboxDbDir =<< mConf)
where
fixPkgDbVer dir =
case takeFileName dir == ghcSandboxPkgDbDir platform ghcVer of
True -> dir
False -> takeDirectory dir </> ghcSandboxPkgDbDir platform ghcVer
ghcSandboxPkgDbDir :: String -> GhcVersion -> String
ghcSandboxPkgDbDir platform ghcVer =
platform ++ "-ghc-" ++ showGhcVersion ghcVer ++ "-packages.conf.d"
extractSandboxDbDir :: String -> Maybe FilePath
extractSandboxDbDir conf = extractValue <$> parse conf
where
key = "package-db:"
keyLen = length key
parse = listToMaybe . filter (key `isPrefixOf`) . lines
extractValue = CabalHelper.Compiletime.Sandbox.dropWhileEnd isSpace . dropWhile isSpace . drop keyLen
dropWhileEnd :: (a -> Bool) -> [a] -> [a]
dropWhileEnd p = foldr (\x xs -> if p x && null xs then [] else x : xs) []