Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Fetching contributors…

Cannot retrieve contributors at this time

file 291 lines (258 sloc) 13.269 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Client.Sandbox
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- UI for the sandboxing functionality.
-----------------------------------------------------------------------------

module Distribution.Client.Sandbox (
#ifdef TEST
    withSandboxBinDirOnSearchPath,
#endif
    sandboxInit,
    sandboxDelete,
    sandboxAddSource,
    sandboxConfigure,
    sandboxBuild,
    sandboxInstall,

    dumpPackageEnvironment
  ) where

import Distribution.Client.Setup
  ( SandboxFlags(..), ConfigFlags(..), ConfigExFlags(..), GlobalFlags(..)
  , InstallFlags(..), globalRepos
  , defaultInstallFlags, defaultConfigExFlags, defaultSandboxLocation
  , installCommand )
import Distribution.Client.Config ( SavedConfig(..), loadConfig )
import Distribution.Client.Configure ( configure )
import Distribution.Client.Install ( install )
import Distribution.Client.PackageEnvironment
  ( PackageEnvironment(..)
  , createPackageEnvironment, tryLoadPackageEnvironment
  , commentPackageEnvironment
  , showPackageEnvironmentWithComments
  , setPackageDB
  , sandboxPackageEnvironmentFile )
import Distribution.Client.SetupWrapper
  ( setupWrapper, SetupScriptOptions(..), defaultSetupScriptOptions )
import Distribution.Client.Targets ( readUserTargets )
import Distribution.Simple.Compiler ( Compiler
                                              , PackageDB(..), PackageDBStack )
import Distribution.Simple.Configure ( configCompilerAux
                                              , interpretPackageDbFlags )
import Distribution.Simple.Program ( ProgramConfiguration
                                              , defaultProgramConfiguration )
import Distribution.Simple.Setup ( Flag(..), toFlag
                                              , BuildFlags(..), HaddockFlags(..)
                                              , buildCommand, fromFlagOrDefault )
import Distribution.Simple.Utils ( die, debug, notice, info
                                              , intercalate
                                              , createDirectoryIfMissingVerbose )
import Distribution.Verbosity ( Verbosity, lessVerbose )
import Distribution.Compat.SetEnv ( setEnv )
import qualified Distribution.Client.Index as Index
import qualified Distribution.Simple.Register as Register
import Control.Exception ( bracket_ )
import Control.Monad ( unless, when )
import Data.Monoid ( mappend, mempty )
import Data.List ( delete )
import System.Directory ( canonicalizePath
                                              , doesDirectoryExist
                                              , getCurrentDirectory
                                              , removeDirectoryRecursive
                                              , removeFile )
import System.Environment ( getEnv )
import System.FilePath ( (</>), getSearchPath
                                              , searchPathSeparator )


-- | Load the default package environment file. In addition to a
-- @PackageEnvironment@, also return a canonical path to the sandbox. Exit with
-- error if the sandbox directory or the package environment file do not exist.
tryLoadSandboxConfig :: Verbosity -> IO (FilePath, PackageEnvironment)
tryLoadSandboxConfig verbosity = do
  pkgEnvDir <- getCurrentDirectory
  (sandboxDir, pkgEnv) <- tryLoadPackageEnvironment verbosity pkgEnvDir
  dirExists <- doesDirectoryExist sandboxDir
  -- TODO: Also check for an initialised package DB?
  unless dirExists $
    die ("No sandbox exists at " ++ sandboxDir)
  info verbosity $ "Using a sandbox located at " ++ sandboxDir
  return (sandboxDir, pkgEnv)

-- | Return the name of the package index file for this package environment.
tryGetIndexFilePath :: PackageEnvironment -> IO FilePath
tryGetIndexFilePath pkgEnv = do
  let paths = globalLocalRepos . savedGlobalFlags . pkgEnvSavedConfig $ pkgEnv
  case paths of
    [] -> die $ "Distribution.Client.Sandbox.tryGetIndexFilePath: " ++
           "no local repos found"
    [p] -> return $ p </> Index.defaultIndexFileName
    _ -> die $ "Distribution.Client.Sandbox.tryGetIndexFilePath: " ++
           "too many local repos found"

-- | Temporarily add $SANDBOX_DIR/bin to $PATH.
withSandboxBinDirOnSearchPath :: FilePath -> IO a -> IO a
withSandboxBinDirOnSearchPath sandboxDir = bracket_ addBinDir rmBinDir
  where
    -- TODO: Instead of modifying the global process state, it'd be better to
    -- set the environment individually for each subprocess invocation. Will
    -- have to wait until the Shell monad is implemented, because otherwise the
    -- change will be too intrusive.
    addBinDir :: IO ()
    addBinDir = do
      oldPath <- getEnv "PATH"
      let newPath = sandboxBin ++ (searchPathSeparator:oldPath)
      setEnv "PATH" newPath

    rmBinDir :: IO ()
    rmBinDir = do
      oldPath <- getSearchPath
      let newPath = intercalate [searchPathSeparator]
                    (delete sandboxBin oldPath)
      setEnv "PATH" newPath

    sandboxBin = sandboxDir </> "bin"

-- | Initialise a package DB for this compiler if it doesn't exist.
initPackageDBIfNeeded :: Verbosity -> ConfigFlags
                         -> Compiler -> ProgramConfiguration
                         -> IO ()
initPackageDBIfNeeded verbosity configFlags comp conf = do
  -- TODO: Is pattern-matching here really safe?
  let [Just (SpecificPackageDB dbPath)] = configPackageDBs configFlags
  packageDBExists <- doesDirectoryExist dbPath
  unless packageDBExists $
    Register.initPackageDB verbosity comp conf dbPath
  when packageDBExists $
    debug verbosity $ "The package database already exists: " ++ dbPath

-- | Entry point for the 'cabal dump-pkgenv' command.
dumpPackageEnvironment :: Verbosity -> SandboxFlags -> IO ()
dumpPackageEnvironment verbosity _sandboxFlags = do
  (sandboxDir, pkgEnv) <- tryLoadSandboxConfig verbosity
  commentPkgEnv <- commentPackageEnvironment sandboxDir
  putStrLn . showPackageEnvironmentWithComments commentPkgEnv $ pkgEnv

-- | Entry point for the 'cabal sandbox-init' command.
sandboxInit :: Verbosity -> SandboxFlags -> GlobalFlags -> IO ()
sandboxInit verbosity sandboxFlags globalFlags = do
  -- Create the sandbox directory.
  let sandboxDir' = fromFlagOrDefault defaultSandboxLocation
                    (sandboxLocation sandboxFlags)
  createDirectoryIfMissingVerbose verbosity True sandboxDir'
  sandboxDir <- canonicalizePath sandboxDir'
  notice verbosity $ "Using a sandbox located at " ++ sandboxDir

  -- Determine which compiler to use (using the value from ~/.cabal/config).
  userConfig <- loadConfig verbosity (globalConfigFile globalFlags) NoFlag
  (comp, conf) <- configCompilerAux (savedConfigureFlags userConfig)

  -- Create the package environment file.
  pkgEnvDir <- getCurrentDirectory
  pkgEnv <- createPackageEnvironment verbosity sandboxDir pkgEnvDir
               comp userConfig

  -- Create the index file if it doesn't exist.
  indexFile <- tryGetIndexFilePath pkgEnv
  Index.createEmpty verbosity indexFile

  -- Create the package DB for this compiler if it doesn't exist. If the user
  -- later chooses a different compiler with -w, the sandbox for that compiler
  -- will be created on demand.
  initPackageDBIfNeeded verbosity
    (savedConfigureFlags . pkgEnvSavedConfig $ pkgEnv) comp conf

-- | Entry point for the 'cabal sandbox-delete' command.
sandboxDelete :: Verbosity -> SandboxFlags -> GlobalFlags -> IO ()
sandboxDelete verbosity sandboxFlags _globalFlags = do
  pkgEnvDir <- getCurrentDirectory
  removeFile (pkgEnvDir </> sandboxPackageEnvironmentFile)
  if sandboxLoc == defaultSandboxLocation
    then do
      sandboxDir <- canonicalizePath sandboxLoc
      notice verbosity $ "Deleting the sandbox located at " ++ sandboxDir
      removeDirectoryRecursive sandboxDir
    else
      die $ "Non-default sandbox location used: " ++ sandboxLoc
      ++ "\nPlease delete manually."
  where
    sandboxLoc = fromFlagOrDefault defaultSandboxLocation
                 (sandboxLocation sandboxFlags)

-- | Entry point for the 'cabal sandbox-add-source' command.
sandboxAddSource :: Verbosity -> SandboxFlags -> [FilePath] -> IO ()
sandboxAddSource verbosity _sandboxFlags buildTreeRefs = do
  (_sandboxDir, pkgEnv) <- tryLoadSandboxConfig verbosity
  indexFile <- tryGetIndexFilePath pkgEnv

  Index.addBuildTreeRefs verbosity indexFile buildTreeRefs

-- | Entry point for the 'cabal sandbox-configure' command.
sandboxConfigure :: Verbosity -> SandboxFlags -> ConfigFlags -> ConfigExFlags
                    -> [String] -> GlobalFlags -> IO ()
sandboxConfigure verbosity
  _sandboxFlags configFlags configExFlags extraArgs globalFlags = do
  (sandboxDir, pkgEnv) <- tryLoadSandboxConfig verbosity

  let config = pkgEnvSavedConfig pkgEnv
      configFlags' = savedConfigureFlags config `mappend` configFlags
      configExFlags' = savedConfigureExFlags config `mappend` configExFlags
      globalFlags' = savedGlobalFlags config `mappend` globalFlags
  (comp, conf) <- configCompilerAux configFlags'

  -- If the user has set the -w option, we may need to create the package DB for
  -- this compiler.
  let configFlags'' = setPackageDB sandboxDir comp configFlags'
  initPackageDBIfNeeded verbosity configFlags'' comp conf

  withSandboxBinDirOnSearchPath sandboxDir $
    configure verbosity
              (configPackageDB' configFlags'') (globalRepos globalFlags')
              comp conf configFlags'' configExFlags' extraArgs

-- | Entry point for the 'cabal sandbox-build' command.
sandboxBuild :: Verbosity -> SandboxFlags -> BuildFlags -> [String] -> IO ()
sandboxBuild verbosity _sandboxFlags buildFlags' extraArgs = do
  -- Check that the sandbox exists.
  (sandboxDir, _) <- tryLoadSandboxConfig verbosity

  let setupScriptOptions = defaultSetupScriptOptions {
        useDistPref = fromFlagOrDefault
                      (useDistPref defaultSetupScriptOptions)
                      (buildDistPref buildFlags)
        }
      buildFlags = buildFlags' {
        buildVerbosity = toFlag verbosity
        }

  withSandboxBinDirOnSearchPath sandboxDir $
    setupWrapper verbosity setupScriptOptions Nothing
      (buildCommand defaultProgramConfiguration) (const buildFlags) extraArgs

-- | Entry point for the 'cabal sandbox-install' command.
sandboxInstall :: Verbosity -> SandboxFlags -> ConfigFlags -> ConfigExFlags
                  -> InstallFlags -> HaddockFlags -> [String] -> GlobalFlags
                  -> IO ()
sandboxInstall verbosity _sandboxFlags _configFlags _configExFlags
  installFlags _haddockFlags _extraArgs _globalFlags
  | fromFlagOrDefault False (installOnly installFlags)
  -- TODO: It'd nice if this picked up the -w flag passed to sandbox-configure.
  -- Right now, running
  --
  -- $ cabal sandbox-init && cabal sandbox-configure -w /path/to/ghc
  -- && cabal sandbox-build && cabal sandbox-install
  --
  -- performs the compilation twice unless you also pass -w to sandbox-install.
  = setupWrapper verbosity defaultSetupScriptOptions Nothing
    installCommand (const mempty) []

sandboxInstall verbosity _sandboxFlags configFlags configExFlags
  installFlags haddockFlags extraArgs globalFlags = do
  (sandboxDir, pkgEnv) <- tryLoadSandboxConfig verbosity
  targets <- readUserTargets verbosity extraArgs

  let config = pkgEnvSavedConfig pkgEnv
      configFlags' = savedConfigureFlags config `mappend` configFlags
      configExFlags' = defaultConfigExFlags `mappend`
                       savedConfigureExFlags config `mappend` configExFlags
      installFlags' = defaultInstallFlags `mappend`
                       savedInstallFlags config `mappend` installFlags
      globalFlags' = savedGlobalFlags config `mappend` globalFlags
  (comp, conf) <- configCompilerAux' configFlags'

  -- If the user has set the -w option, we may need to create the package DB for
  -- this compiler.
  let configFlags'' = setPackageDB sandboxDir comp configFlags'
  initPackageDBIfNeeded verbosity configFlags'' comp conf

  withSandboxBinDirOnSearchPath sandboxDir $
    install verbosity
            (configPackageDB' configFlags'') (globalRepos globalFlags')
            comp conf
            globalFlags' configFlags'' configExFlags' installFlags' haddockFlags
            targets

configPackageDB' :: ConfigFlags -> PackageDBStack
configPackageDB' cfg =
  interpretPackageDbFlags userInstall (configPackageDBs cfg)
  where
    userInstall = fromFlagOrDefault True (configUserInstall cfg)

configCompilerAux' :: ConfigFlags
                      -> IO (Compiler, ProgramConfiguration)
configCompilerAux' configFlags =
  configCompilerAux configFlags
    --FIXME: make configCompilerAux use a sensible verbosity
    { configVerbosity = fmap lessVerbose (configVerbosity configFlags) }
Something went wrong with that request. Please try again.