Configure.hs 16 KB
Newer Older
1
{-# LANGUAGE CPP #-}
2 3 4 5 6 7 8 9 10 11 12 13 14 15
-----------------------------------------------------------------------------
-- |
-- Module      :  Distribution.Client.Configure
-- Copyright   :  (c) David Himmelstrup 2005,
--                    Duncan Coutts 2005
-- License     :  BSD-like
--
-- Maintainer  :  cabal-devel@haskell.org
-- Portability :  portable
--
-- High level interface to configuring a package.
-----------------------------------------------------------------------------
module Distribution.Client.Configure (
    configure,
16
    configureSetupScript,
Mikhail Glushenkov's avatar
Mikhail Glushenkov committed
17
    chooseCabalVersion,
18
    checkConfigExFlags
19 20 21
  ) where

import Distribution.Client.Dependency
22
import Distribution.Client.Dependency.Types
23
         ( ConstraintSource(..)
24
         , LabeledPackageConstraint(..), showConstraintSource )
25
import qualified Distribution.Client.InstallPlan as InstallPlan
26
import Distribution.Client.InstallPlan (SolverInstallPlan)
27
import Distribution.Client.IndexUtils as IndexUtils
28
         ( getSourcePackages, getInstalledPackages )
29
import Distribution.Client.Setup
Edsko de Vries's avatar
Edsko de Vries committed
30 31
         ( ConfigExFlags(..), configureCommand, filterConfigureFlags
         , RepoContext(..) )
32
import Distribution.Client.Types as Source
33 34
import Distribution.Client.SetupWrapper
         ( setupWrapper, SetupScriptOptions(..), defaultSetupScriptOptions )
35
import Distribution.Client.Targets
36
         ( userToPackageConstraint, userConstraintPackageName )
37 38
import Distribution.Package (PackageId)
import Distribution.Client.JobControl (Lock)
39

40 41 42 43 44 45 46 47
import qualified Distribution.Solver.Types.ComponentDeps as CD
import           Distribution.Solver.Types.OptionalStanza
import           Distribution.Solver.Types.PackageIndex
                   ( PackageIndex, elemByPackageName )
import           Distribution.Solver.Types.PkgConfigDb
                   (PkgConfigDb, readPkgConfigDb)
import           Distribution.Solver.Types.SourcePackage

48
import Distribution.Simple.Compiler
49
         ( Compiler, CompilerInfo, compilerInfo, PackageDB(..), PackageDBStack )
50
import Distribution.Simple.Program (ProgramConfiguration )
51
import Distribution.Simple.Setup
52 53
         ( ConfigFlags(..), AllowNewer(..)
         , fromFlag, toFlag, flagToMaybe, fromFlagOrDefault )
54 55
import Distribution.Simple.PackageIndex
         ( InstalledPackageIndex, lookupPackageName )
56 57 58
import Distribution.Simple.Utils
         ( defaultPackageDesc )
import Distribution.Package
59
         ( Package(..), UnitId, packageName
60 61 62
         , Dependency(..), thisPackageVersion
         )
import qualified Distribution.PackageDescription as PkgDesc
63 64 65 66 67
import Distribution.PackageDescription.Parse
         ( readPackageDescription )
import Distribution.PackageDescription.Configuration
         ( finalizePackageDescription )
import Distribution.Version
68
         ( anyVersion, thisVersion )
69
import Distribution.Simple.Utils as Utils
70
         ( warn, notice, debug, die )
71
import Distribution.Simple.Setup
72
         ( isAllowNewer )
73
import Distribution.System
74
         ( Platform )
75
import Distribution.Text ( display )
76 77
import Distribution.Verbosity as Verbosity
         ( Verbosity )
78
import Distribution.Version
Mikhail Glushenkov's avatar
Mikhail Glushenkov committed
79
         ( Version(..), VersionRange, orLaterVersion )
80

81
import Control.Monad (unless)
82
#if !MIN_VERSION_base(4,8,0)
83
import Data.Monoid (Monoid(..))
84
#endif
85
import Data.Maybe (isJust, fromMaybe)
86

Mikhail Glushenkov's avatar
Mikhail Glushenkov committed
87 88
-- | Choose the Cabal version such that the setup scripts compiled against this
-- version will support the given command-line flags.
89 90
chooseCabalVersion :: ConfigFlags -> Maybe Version -> VersionRange
chooseCabalVersion configFlags maybeVersion =
Mikhail Glushenkov's avatar
Mikhail Glushenkov committed
91 92
  maybe defaultVersionRange thisVersion maybeVersion
  where
Mikhail Glushenkov's avatar
Mikhail Glushenkov committed
93 94
    -- Cabal < 1.19.2 doesn't support '--exact-configuration' which is needed
    -- for '--allow-newer' to work.
95 96
    allowNewer = isAllowNewer
                 (fromMaybe AllowNewerNone $ configAllowNewer configFlags)
Mikhail Glushenkov's avatar
Mikhail Glushenkov committed
97 98 99 100 101

    defaultVersionRange = if allowNewer
                          then orLaterVersion (Version [1,19,2] [])
                          else anyVersion

102 103
-- | Configure the package found in the local directory
configure :: Verbosity
104
          -> PackageDBStack
Edsko de Vries's avatar
Edsko de Vries committed
105
          -> RepoContext
106
          -> Compiler
107
          -> Platform
108
          -> ProgramConfiguration
109
          -> ConfigFlags
110
          -> ConfigExFlags
111 112
          -> [String]
          -> IO ()
Edsko de Vries's avatar
Edsko de Vries committed
113
configure verbosity packageDBs repoCtxt comp platform conf
114 115
  configFlags configExFlags extraArgs = do

116
  installedPkgIndex <- getInstalledPackages verbosity comp packageDBs conf
Edsko de Vries's avatar
Edsko de Vries committed
117
  sourcePkgDb       <- getSourcePackages    verbosity repoCtxt
118 119
  pkgConfigDb       <- readPkgConfigDb      verbosity conf

120 121
  checkConfigExFlags verbosity installedPkgIndex
                     (packageIndex sourcePkgDb) configExFlags
122

123
  progress <- planLocalPackage verbosity comp platform configFlags configExFlags
124
                               installedPkgIndex sourcePkgDb pkgConfigDb
125 126

  notice verbosity "Resolving dependencies..."
127 128
  maybePlan <- foldProgress logMsg (return . Left) (return . Right)
                            progress
129
  case maybePlan of
130
    Left message -> do
131 132
      warn verbosity $
           "solver failed to find a solution:\n"
133 134
        ++ message
        ++ "Trying configure anyway."
135 136
      setupWrapper verbosity (setupScriptOptions installedPkgIndex Nothing)
        Nothing configureCommand (const configFlags) extraArgs
137

138 139 140
    Right installPlan0 ->
     let installPlan = InstallPlan.configureInstallPlan installPlan0
     in case InstallPlan.ready installPlan of
141
      [pkg@(ReadyPackage
Edward Z. Yang's avatar
Edward Z. Yang committed
142
              (ConfiguredPackage _ (SourcePackage _ _ (LocalUnpackedPackage _) _)
143
                                 _ _ _))] -> do
144
        configurePackage verbosity
145
          platform (compilerInfo comp)
146
          (setupScriptOptions installedPkgIndex (Just pkg))
147 148 149 150 151 152
          configFlags pkg extraArgs

      _ -> die $ "internal error: configure install plan should have exactly "
              ++ "one local ready package."

  where
153
    setupScriptOptions :: InstalledPackageIndex
154
                       -> Maybe ReadyPackage
155
                       -> SetupScriptOptions
156 157 158 159 160 161 162 163 164 165
    setupScriptOptions =
      configureSetupScript
        packageDBs
        comp
        platform
        conf
        (fromFlagOrDefault
           (useDistPref defaultSetupScriptOptions)
           (configDistPref configFlags))
        (chooseCabalVersion
166
           configFlags
167 168 169
           (flagToMaybe (configCabalVersion configExFlags)))
        Nothing
        False
170

171 172
    logMsg message rest = debug verbosity message >> rest

173 174 175 176 177 178 179 180 181
configureSetupScript :: PackageDBStack
                     -> Compiler
                     -> Platform
                     -> ProgramConfiguration
                     -> FilePath
                     -> VersionRange
                     -> Maybe Lock
                     -> Bool
                     -> InstalledPackageIndex
182
                     -> Maybe ReadyPackage
183 184 185 186 187 188 189 190 191 192 193 194
                     -> SetupScriptOptions
configureSetupScript packageDBs
                     comp
                     platform
                     conf
                     distPref
                     cabalVersion
                     lock
                     forceExternal
                     index
                     mpkg
  = SetupScriptOptions {
195 196 197 198 199 200 201 202 203 204 205 206
      useCabalVersion          = cabalVersion
    , useCabalSpecVersion      = Nothing
    , useCompiler              = Just comp
    , usePlatform              = Just platform
    , usePackageDB             = packageDBs'
    , usePackageIndex          = index'
    , useProgramConfig         = conf
    , useDistPref              = distPref
    , useLoggingHandle         = Nothing
    , useWorkingDir            = Nothing
    , setupCacheLock           = lock
    , useWin32CleanHack        = False
207 208 209 210 211 212 213 214
    , forceExternalSetupMethod = forceExternal
      -- If we have explicit setup dependencies, list them; otherwise, we give
      -- the empty list of dependencies; ideally, we would fix the version of
      -- Cabal here, so that we no longer need the special case for that in
      -- `compileSetupExecutable` in `externalSetupMethod`, but we don't yet
      -- know the version of Cabal at this point, but only find this there.
      -- Therefore, for now, we just leave this blank.
    , useDependencies          = fromMaybe [] explicitSetupDeps
215 216
    , useDependenciesExclusive = not defaultSetupDeps && isJust explicitSetupDeps
    , useVersionMacros         = not defaultSetupDeps && isJust explicitSetupDeps
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
    }
  where
    -- When we are compiling a legacy setup script without an explicit
    -- setup stanza, we typically want to allow the UserPackageDB for
    -- finding the Cabal lib when compiling any Setup.hs even if we're doing
    -- a global install. However we also allow looking in a specific package
    -- db.
    packageDBs' :: PackageDBStack
    index'      :: Maybe InstalledPackageIndex
    (packageDBs', index') =
      case packageDBs of
        (GlobalPackageDB:dbs) | UserPackageDB `notElem` dbs
                              , Nothing <- explicitSetupDeps
            -> (GlobalPackageDB:UserPackageDB:dbs, Nothing)
        -- but if the user is using an odd db stack, don't touch it
        _otherwise -> (packageDBs, Just index)

234 235
    maybeSetupBuildInfo :: Maybe PkgDesc.SetupBuildInfo
    maybeSetupBuildInfo = do
236
      ReadyPackage cpkg <- mpkg
237
      let gpkg = packageDescription (confPkgSource cpkg)
238 239 240 241 242 243 244 245 246 247 248 249
      PkgDesc.setupBuildInfo (PkgDesc.packageDescription gpkg)

    -- Was a default 'custom-setup' stanza added by 'cabal-install' itself? If
    -- so, 'setup-depends' must not be exclusive. See #3199.
    defaultSetupDeps :: Bool
    defaultSetupDeps = maybe False PkgDesc.defaultSetupDepends
                       maybeSetupBuildInfo

    explicitSetupDeps :: Maybe [(UnitId, PackageId)]
    explicitSetupDeps = do
      -- Check if there is an explicit setup stanza.
      _buildInfo <- maybeSetupBuildInfo
250
      -- Return the setup dependencies computed by the solver
251
      ReadyPackage cpkg <- mpkg
252 253
      return [ ( uid, srcid )
             | ConfiguredId srcid uid <- CD.setupDeps (confPkgDeps cpkg)
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
-- | Warn if any constraints or preferences name packages that are not in the
-- source package index or installed package index.
checkConfigExFlags :: Package pkg
                   => Verbosity
                   -> InstalledPackageIndex
                   -> PackageIndex pkg
                   -> ConfigExFlags
                   -> IO ()
checkConfigExFlags verbosity installedPkgIndex sourcePkgIndex flags = do
  unless (null unknownConstraints) $ warn verbosity $
             "Constraint refers to an unknown package: "
          ++ showConstraint (head unknownConstraints)
  unless (null unknownPreferences) $ warn verbosity $
             "Preference refers to an unknown package: "
          ++ display (head unknownPreferences)
  where
    unknownConstraints = filter (unknown . userConstraintPackageName . fst) $
                         configExConstraints flags
    unknownPreferences = filter (unknown . \(Dependency name _) -> name) $
                         configPreferences flags
    unknown pkg = null (lookupPackageName installedPkgIndex pkg)
               && not (elemByPackageName sourcePkgIndex pkg)
    showConstraint (uc, src) =
        display uc ++ " (" ++ showConstraintSource src ++ ")"

281 282 283 284
-- | Make an 'InstallPlan' for the unpacked package in the current directory,
-- and all its dependencies.
--
planLocalPackage :: Verbosity -> Compiler
285
                 -> Platform
286
                 -> ConfigFlags -> ConfigExFlags
287
                 -> InstalledPackageIndex
288
                 -> SourcePackageDb
289
                 -> PkgConfigDb
290
                 -> IO (Progress String String SolverInstallPlan)
291
planLocalPackage verbosity comp platform configFlags configExFlags
292
  installedPkgIndex (SourcePackageDb _ packagePrefs) pkgConfigDb = do
293
  pkg <- readPackageDescription verbosity =<< defaultPackageDesc verbosity
294 295
  solver <- chooseSolver verbosity (fromFlag $ configSolver configExFlags)
            (compilerInfo comp)
296 297

  let -- We create a local package and ask to resolve a dependency on it
298 299
      localPkg = SourcePackage {
        packageInfoId             = packageId pkg,
300
        packageDescription        = pkg,
301 302
        packageSource             = LocalUnpackedPackage ".",
        packageDescrOverride      = Nothing
303
      }
304

305 306 307 308
      testsEnabled = fromFlagOrDefault False $ configTests configFlags
      benchmarksEnabled =
        fromFlagOrDefault False $ configBenchmarks configFlags

309
      resolverParams =
310 311
          removeUpperBounds
          (fromMaybe AllowNewerNone $ configAllowNewer configFlags)
312

313
        . addPreferences
314 315 316 317 318 319
            -- preferences from the config file or command line
            [ PackageVersionPreference name ver
            | Dependency name ver <- configPreferences configExFlags ]

        . addConstraints
            -- version constraints from the config file or command line
Mikhail Glushenkov's avatar
Mikhail Glushenkov committed
320 321
            -- TODO: should warn or error on constraints that are not on direct
            -- deps or flag constraints not on the package in question.
322
            [ LabeledPackageConstraint (userToPackageConstraint uc) src
323
            | (uc, src) <- configExConstraints configExFlags ]
324 325 326

        . addConstraints
            -- package flags from the config file or command line
327 328
            [ let pc = PackageConstraintFlags (packageName pkg)
                       (configConfigurationsFlags configFlags)
329 330
              in LabeledPackageConstraint pc ConstraintSourceConfigFlagOrTarget
            ]
331

332 333
        . addConstraints
            -- '--enable-tests' and '--enable-benchmarks' constraints from
334
            -- the config file or command line
335 336 337
            [ let pc = PackageConstraintStanzas (packageName pkg) $
                       [ TestStanzas  | testsEnabled ] ++
                       [ BenchStanzas | benchmarksEnabled ]
338
              in LabeledPackageConstraint pc ConstraintSourceConfigFlagOrTarget
339 340
            ]

341
        $ standardInstallPolicy
342 343
            installedPkgIndex
            (SourcePackageDb mempty packagePrefs)
344
            [SpecificSourcePackage localPkg]
345

346
  return (resolveDependencies platform (compilerInfo comp) pkgConfigDb solver resolverParams)
347

348

349
-- | Call an installer for an 'SourcePackage' but override the configure
350 351
-- flags with the ones given by the 'ReadyPackage'. In particular the
-- 'ReadyPackage' specifies an exact 'FlagAssignment' and exactly
352 353 354
-- versioned package dependencies. So we ignore any previous partial flag
-- assignment or dependency constraints and use the new ones.
--
355 356
-- NB: when updating this function, don't forget to also update
-- 'installReadyPackage' in D.C.Install.
357
configurePackage :: Verbosity
358
                 -> Platform -> CompilerInfo
359
                 -> SetupScriptOptions
360
                 -> ConfigFlags
361
                 -> ReadyPackage
362 363
                 -> [String]
                 -> IO ()
364
configurePackage verbosity platform comp scriptOptions configFlags
Edward Z. Yang's avatar
Edward Z. Yang committed
365
                 (ReadyPackage (ConfiguredPackage ipid spkg flags stanzas deps))
366
                 extraArgs =
367 368 369 370 371

  setupWrapper verbosity
    scriptOptions (Just pkg) configureCommand configureFlags extraArgs

  where
372
    gpkg = packageDescription spkg
373
    configureFlags   = filterConfigureFlags configFlags {
Edward Z. Yang's avatar
Edward Z. Yang committed
374
      configIPID = toFlag (display ipid),
375
      configConfigurationsFlags = flags,
376 377 378
      -- We generate the legacy constraints as well as the new style precise
      -- deps.  In the end only one set gets passed to Setup.hs configure,
      -- depending on the Cabal version we are talking to.
379 380 381 382
      configConstraints  = [ thisPackageVersion srcid
                           | ConfiguredId srcid _uid <- CD.nonSetupDeps deps ],
      configDependencies = [ (packageName srcid, uid)
                           | ConfiguredId srcid uid <- CD.nonSetupDeps deps ],
383 384
      -- Use '--exact-configuration' if supported.
      configExactConfiguration = toFlag True,
Mikhail Glushenkov's avatar
Mikhail Glushenkov committed
385 386 387
      configVerbosity          = toFlag verbosity,
      configBenchmarks         = toFlag (BenchStanzas `elem` stanzas),
      configTests              = toFlag (TestStanzas `elem` stanzas)
388 389 390
    }

    pkg = case finalizePackageDescription flags
391
           (const True)
392
           platform comp [] (enableStanzas stanzas gpkg) of
393
      Left _ -> error "finalizePackageDescription ReadyPackage failed"
394
      Right (desc, _) -> desc