Configure.hs 28.2 KB
Newer Older
1 2
-----------------------------------------------------------------------------
-- |
ijones's avatar
ijones committed
3
-- Module      :  Distribution.Simple.Configure
4
-- Copyright   :  Isaac Jones 2003-2005
5 6 7
-- 
-- Maintainer  :  Isaac Jones <ijones@syntaxpolice.org>
-- Stability   :  alpha
ijones's avatar
ijones committed
8
-- Portability :  portable
9
--
ijones's avatar
ijones committed
10
-- Explanation: Perform the \"@.\/setup configure@\" action.
Ross Paterson's avatar
Ross Paterson committed
11
-- Outputs the @dist\/setup-config@ file.
12

ijones's avatar
ijones committed
13
{- All rights reserved.
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

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above
      copyright notice, this list of conditions and the following
      disclaimer in the documentation and/or other materials provided
      with the distribution.

    * Neither the name of Isaac Jones nor the names of other
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -}

ijones's avatar
ijones committed
43 44
module Distribution.Simple.Configure (configure,
                                      writePersistBuildConfig,
ijones's avatar
ijones committed
45
                                      getPersistBuildConfig,
46
                                      checkPersistBuildConfig,
47
                                      maybeGetPersistBuildConfig,
48
--                                      getConfiguredPkgDescr,
ijones's avatar
ijones committed
49
                                      localBuildInfoFile,
50
                                      getInstalledPackages,
Simon Marlow's avatar
Simon Marlow committed
51
				      configDependency,
52
                                      configCompiler, configCompilerAux,
53
                                      ccLdOptionsBuildInfo,
ijones's avatar
ijones committed
54
                                     )
ijones's avatar
ijones committed
55
    where
56

57
import Distribution.Simple.Compiler
58
    ( CompilerFlavor(..), Compiler(compilerFlavor), compilerVersion, showCompilerId
59
    , unsupportedExtensions, PackageDB(..) )
60
import Distribution.Package
61
    ( PackageIdentifier(PackageIdentifier), packageVersion, Package(..)
62 63
    , showPackageId, parsePackageId
    , Dependency(..), showDependency )
64
import Distribution.InstalledPackageInfo
65
    ( InstalledPackageInfo, emptyInstalledPackageInfo )
66
import qualified Distribution.InstalledPackageInfo as InstalledPackageInfo
67
    ( InstalledPackageInfo_(package,depends) )
68
import qualified Distribution.Simple.PackageIndex as PackageIndex
69
import Distribution.Simple.PackageIndex (PackageIndex)
70
import Distribution.PackageDescription as PD
71
    ( PackageDescription(..), GenericPackageDescription(..)
72
    , Library(..), hasLibs, Executable(..), BuildInfo(..)
73
    , HookedBuildInfo, updatePackageDescription, allBuildInfo )
74
import Distribution.PackageDescription.Configuration
75
    ( finalizePackageDescription )
76 77
import Distribution.PackageDescription.Check
    ( PackageCheck(..), checkPackage, checkPackageFiles )
78 79
import Distribution.Compat.ReadP
    ( readP_to_S )
80
import Distribution.Simple.Program
81
    ( Program(..), ProgramLocation(..), ConfiguredProgram(..)
Duncan Coutts's avatar
Duncan Coutts committed
82 83
    , ProgramConfiguration, defaultProgramConfiguration
    , configureAllKnownPrograms, knownPrograms
84
    , userSpecifyArgs, userSpecifyPath
85 86
    , lookupKnownProgram, requireProgram, pkgConfigProgram
    , rawSystemProgramStdoutConf )
87
import Distribution.Simple.Setup
88
    ( ConfigFlags(..), CopyDest(..), fromFlag, fromFlagOrDefault, flagToMaybe )
89
import Distribution.Simple.InstallDirs
90
    ( InstallDirs(..), defaultInstallDirs, combineInstallDirs )
91
import Distribution.Simple.LocalBuildInfo
92
    ( LocalBuildInfo(..), absoluteInstallDirs
93
    , prefixRelativeInstallDirs )
94 95
import Distribution.Simple.BuildPaths
    ( distPref )
96
import Distribution.Simple.Utils
97
    ( die, warn, info, setupMessage, createDirectoryIfMissingVerbose
98
    , intercalate, comparing, cabalVersion, cabalBootstrapping )
99 100 101
import Distribution.Simple.Register
    ( removeInstalledConfig )
import Distribution.System
102
    ( OS(..), buildOS, buildArch )
103
import Distribution.Version
104
    ( Version(..), VersionRange(..), showVersion, readVersion
105
    , showVersionRange, orLaterVersion, withinRange )
106
import Distribution.Verbosity
107
    ( Verbosity, lessVerbose )
108

109 110 111 112 113
import qualified Distribution.Simple.GHC  as GHC
import qualified Distribution.Simple.JHC  as JHC
import qualified Distribution.Simple.NHC  as NHC
import qualified Distribution.Simple.Hugs as Hugs

114
import Control.Monad
115
    ( when, unless, foldM )
116 117
import Control.Exception as Exception
    ( catch )
118
import Data.List
119
    ( nub, partition, isPrefixOf, maximumBy )
120
import Data.Maybe
121
    ( fromMaybe, isNothing )
122 123
import Data.Monoid
    ( Monoid(..) )
124
import System.Directory
125
    ( doesFileExist, getModificationTime, createDirectoryIfMissing )
126 127 128
import System.Exit
    ( ExitCode(..), exitWith )
import System.FilePath
129
    ( (</>), isAbsolute )
130
import qualified System.Info
131
    ( compilerName, compilerVersion )
132 133 134 135 136
import System.IO
    ( hPutStrLn, stderr )
import Text.PrettyPrint.HughesPJ
    ( comma, punctuate, render, nest, sep )
    
137
import Prelude hiding (catch)
138

139 140
tryGetConfigStateFile :: (Read a) => FilePath -> IO (Either String a)
tryGetConfigStateFile filename = do
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
  exists <- doesFileExist filename
  if not exists
    then return (Left missing)
    else do 
      str <- readFile filename
      return $ case lines str of
        [headder, rest] -> case checkHeader headder of
          Just msg -> Left msg
          Nothing  -> case reads rest of
            [(bi,_)] -> Right bi
            _        -> Left cantParse
        _            -> Left cantParse
  where
    checkHeader :: String -> Maybe String
    checkHeader header = case parseHeader header of
      Just (cabalId, compilerId)
        | cabalId
       == currentCabalId -> Nothing
        | otherwise      -> Just (badVersion cabalId compilerId)
      Nothing            -> Just cantParse

    missing   = "Run the 'configure' command first."
    cantParse = "Saved package config file seems to be corrupt. "
             ++ "Try re-running the 'configure' command."
    badVersion cabalId compilerId
              = "You need to re-run the 'configure' command. "
             ++ "The version of Cabal being used has changed (was "
             ++ showPackageId cabalId ++ ", now "
             ++ showPackageId currentCabalId ++ ")."
             ++ badcompiler compilerId
    badcompiler compilerId | compilerId == currentCompilerId = ""
                           | otherwise
              = " Additionally the compiler is different (was "
             ++ showPackageId compilerId ++ ", now "
             ++ showPackageId currentCompilerId
             ++ ") which is probably the cause of the problem."
177

178 179 180 181
-- internal function
tryGetPersistBuildConfig :: IO (Either String LocalBuildInfo)
tryGetPersistBuildConfig = tryGetConfigStateFile localBuildInfoFile

182 183 184
-- |Read the 'localBuildInfoFile'.  Error if it doesn't exist.  Also
-- fail if the file containing LocalBuildInfo is older than the .cabal
-- file, indicating that a re-configure is required.
185 186 187 188 189
getPersistBuildConfig :: IO LocalBuildInfo
getPersistBuildConfig = do
  lbi <- tryGetPersistBuildConfig
  either die return lbi

ijones's avatar
ijones committed
190
-- |Try to read the 'localBuildInfoFile'.
191 192 193 194
maybeGetPersistBuildConfig :: IO (Maybe LocalBuildInfo)
maybeGetPersistBuildConfig = do
  lbi <- tryGetPersistBuildConfig
  return $ either (const Nothing) Just lbi
ijones's avatar
ijones committed
195

ijones's avatar
ijones committed
196 197
-- |After running configure, output the 'LocalBuildInfo' to the
-- 'localBuildInfoFile'.
ijones's avatar
ijones committed
198
writePersistBuildConfig :: LocalBuildInfo -> IO ()
199
writePersistBuildConfig lbi = do
Ross Paterson's avatar
Ross Paterson committed
200
  createDirectoryIfMissing False distPref
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
  writeFile localBuildInfoFile $ showHeader pkgid
                              ++ '\n' : show lbi
  where
    pkgid   = packageId (localPkgDescr lbi)

showHeader :: PackageIdentifier -> String
showHeader pkgid =
     "Saved package config for " ++ showPackageId pkgid
  ++ " written by " ++ showPackageId currentCabalId
  ++      " using " ++ showPackageId currentCompilerId
  where

currentCabalId :: PackageIdentifier
currentCabalId = PackageIdentifier "Cabal" currentVersion
  where currentVersion | cabalBootstrapping = Version [0] []
                       | otherwise          = cabalVersion

currentCompilerId :: PackageIdentifier
currentCompilerId = PackageIdentifier System.Info.compilerName
                                      System.Info.compilerVersion

parseHeader :: String -> Maybe (PackageIdentifier, PackageIdentifier) 
parseHeader header = case words header of
  ["Saved", "package", "config", "for", pkgid,
   "written", "by", cabalid, "using", compilerid]
    -> case (readPackageId pkgid,
             readPackageId cabalid,
             readPackageId compilerid) of
        (Just _,
         Just cabalid',
         Just compilerid') -> Just (cabalid', compilerid')
        _                  -> Nothing
  _                        -> Nothing
  where readPackageId str = case readP_to_S parsePackageId str of
          [] -> Nothing
          ok -> Just (fst (last ok))
237

238 239 240 241 242 243 244 245 246
-- |Check that localBuildInfoFile is up-to-date with respect to the
-- .cabal file.
checkPersistBuildConfig :: FilePath -> IO ()
checkPersistBuildConfig pkg_descr_file = do
  t0 <- getModificationTime pkg_descr_file
  t1 <- getModificationTime localBuildInfoFile
  when (t0 > t1) $
    die (pkg_descr_file ++ " has been changed, please re-configure.")

Ross Paterson's avatar
Ross Paterson committed
247
-- |@dist\/setup-config@
248
localBuildInfoFile :: FilePath
Ross Paterson's avatar
Ross Paterson committed
249
localBuildInfoFile = distPref </> "setup-config"
ijones's avatar
ijones committed
250

251
-- -----------------------------------------------------------------------------
ijones's avatar
ijones committed
252 253
-- * Configuration
-- -----------------------------------------------------------------------------
254

255 256
-- |Perform the \"@.\/setup configure@\" action.
-- Returns the @.setup-config@ file.
257
configure :: ( Either GenericPackageDescription PackageDescription
258
             , HookedBuildInfo) 
259
          -> ConfigFlags -> IO LocalBuildInfo
260
configure (pkg_descr0, pbi) cfg
261
  = do  let verbosity = fromFlag (configVerbose cfg)
262 263

	setupMessage verbosity "Configuring"
264
                     (packageId (either packageDescription id pkg_descr0))
265

266
	createDirectoryIfMissingVerbose (lessVerbose verbosity) True distPref
267

268 269 270 271
        let programsConfig = 
                flip (foldr (uncurry userSpecifyArgs)) (configProgramArgs cfg)
              . flip (foldr (uncurry userSpecifyPath)) (configProgramPaths cfg)
              $ configPrograms cfg
272 273 274 275 276
            userInstall = fromFlag (configUserInstall cfg)
	    defaultPackageDB | userInstall = UserPackageDB
	                     | otherwise   = GlobalPackageDB
	    packageDb   = fromFlagOrDefault defaultPackageDB
	                                    (configPackageDB cfg)
277

278
	-- detect compiler
279 280 281 282
	(comp, programsConfig') <- configCompiler
          (flagToMaybe $ configHcFlavor cfg)
          (flagToMaybe $ configHcPath cfg) (flagToMaybe $ configHcPkg cfg)
          programsConfig (lessVerbose verbosity)
283 284
        let version = compilerVersion comp
            flavor  = compilerFlavor comp
285

Simon Marlow's avatar
Simon Marlow committed
286
        -- FIXME: currently only GHC has hc-pkg
287 288
        maybePackageIndex <- getInstalledPackages (lessVerbose verbosity) comp
                               packageDb programsConfig'
289

290 291 292 293
        (pkg_descr, flags) <- case pkg_descr0 of
            Left ppd -> 
                case finalizePackageDescription 
                       (configConfigurationsFlags cfg)
294
                       maybePackageIndex
295
                       Distribution.System.buildOS
296
                       Distribution.System.buildArch
297
                       (flavor, version)
298 299 300 301 302 303 304 305 306
                       ppd
                of Right r -> return r
                   Left missing -> 
                       die $ "At least the following dependencies are missing:\n"
                         ++ (render . nest 4 . sep . punctuate comma $ 
                             map showDependency missing)
            Right pd -> return (pd,[])
              

307
        when (not (null flags)) $
308
          info verbosity $ "Flags chosen: " ++ (intercalate ", " .
309 310
                      map (\(n,b) -> n ++ "=" ++ show b) $ flags)

311
        checkPackageProblems verbosity (updatePackageDescription pbi pkg_descr)
312

313 314 315 316 317 318 319 320 321 322 323 324 325 326
        let packageIndex = fromMaybe bogusPackageIndex maybePackageIndex
            -- FIXME: For Hugs, nhc98 and other compilers we do not know what
            -- packages are already installed, so we just make some up, pretend
            -- that they do exist and just hope for the best. We make them up
            -- based on what other package the package we're currently building
            -- happens to depend on. See 'inventBogusPackageId' below.
            -- Let's hope they really are installed... :-)
            bogusDependencies = map inventBogusPackageId (buildDepends pkg_descr)
            bogusPackageIndex = PackageIndex.fromList
              [ emptyInstalledPackageInfo {
                  InstalledPackageInfo.package = bogusPackageId
                  -- note that these bogus packages have no other dependencies
                }
              | bogusPackageId <- bogusDependencies ]
327
        dep_pkgs <- case flavor of
328 329
          GHC -> mapM (configDependency verbosity packageIndex) (buildDepends pkg_descr)
          JHC -> mapM (configDependency verbosity packageIndex) (buildDepends pkg_descr)
330
          _   -> return bogusDependencies
Simon Marlow's avatar
Simon Marlow committed
331

332
        packageDependsIndex <-
333
          case PackageIndex.dependencyClosure packageIndex dep_pkgs of
334 335 336
            Left packageDependsIndex -> return packageDependsIndex
            Right broken ->
              die $ "The following installed packages are broken because other"
337 338
                 ++ " packages they depend on are missing. These broken "
                 ++ "packages must be rebuilt before they can be used.\n"
339
                 ++ unlines [ "package "
340
                           ++ showPackageId (packageId pkg)
341 342 343 344
                           ++ " is broken due to missing package "
                           ++ intercalate ", " (map showPackageId deps)
                            | (pkg, deps) <- broken ]

345 346 347 348 349
        let pseudoTopPkg = emptyInstalledPackageInfo {
                InstalledPackageInfo.package = packageId pkg_descr,
                InstalledPackageInfo.depends = dep_pkgs
              }
        case PackageIndex.dependencyInconsistencies packageDependsIndex pseudoTopPkg of
350 351 352
          [] -> return ()
          inconsistencies ->
            warn verbosity $
353
                 "This package indirectly depends on multiple versions of the same "
354 355 356 357 358
              ++ "package. This is highly likely to cause a compile failure.\n"
              ++ unlines [ "package " ++ showPackageId pkg ++ " requires "
                        ++ showPackageId (PackageIdentifier name ver)
                         | (name, uses) <- inconsistencies
                         , (pkg, ver) <- uses ]
Simon Marlow's avatar
Simon Marlow committed
359 360 361

	removeInstalledConfig

362
	-- installation directories
363
	defaultDirs <- defaultInstallDirs flavor userInstall (hasLibs pkg_descr)
364 365
	let installDirs = combineInstallDirs fromFlagOrDefault
                            defaultDirs (configInstallDirs cfg)
366

367
        -- check extensions
368
        let extlist = nub $ concatMap extensions (allBuildInfo pkg_descr)
369
        let exts = unsupportedExtensions comp extlist
370
        unless (null exts) $ warn verbosity $ -- Just warn, FIXME: Should this be an error?
371
            show flavor ++ " does not support the following extensions:\n " ++
372
            intercalate ", " (map show exts)
373

374
        let requiredBuildTools = concatMap buildTools (allBuildInfo pkg_descr)
375 376
        programsConfig'' <-
              configureAllKnownPrograms (lessVerbose verbosity) programsConfig'
377
          >>= configureRequiredPrograms verbosity requiredBuildTools
378
        
379 380
        (pkg_descr', programsConfig''') <- configurePkgconfigPackages verbosity
                                            pkg_descr programsConfig''
381

382
	split_objs <- 
383
	   if not (fromFlag $ configSplitObjs cfg)
384
		then return False
385 386
		else case flavor of
			    GHC | version >= Version [6,5] [] -> return True
387
	    		    _ -> do warn verbosity
Ian Lynagh's avatar
Ian Lynagh committed
388 389
                                         ("this compiler does not support " ++
					  "--enable-split-objs; ignoring")
390 391
				    return False

392
	let lbi = LocalBuildInfo{
393 394
		    installDirTemplates = installDirs,
		    compiler            = comp,
Duncan Coutts's avatar
Duncan Coutts committed
395
		    buildDir            = distPref </> "build",
396 397 398
		    scratchDir          = fromFlagOrDefault
                                            (distPref </> "scratch")
                                            (configScratchDir cfg),
399
		    packageDeps         = dep_pkgs,
400
                    installedPkgs       = packageDependsIndex,
401
                    pkgDescrFile        = Nothing,
402
		    localPkgDescr       = pkg_descr',
403 404 405 406 407 408 409
		    withPrograms        = programsConfig''',
		    withVanillaLib      = fromFlag $ configVanillaLib cfg,
		    withProfLib         = fromFlag $ configProfLib cfg,
		    withSharedLib       = fromFlag $ configSharedLib cfg,
		    withProfExe         = fromFlag $ configProfExe cfg,
		    withOptimization    = fromFlag $ configOptimization cfg,
		    withGHCiLib         = fromFlag $ configGHCiLib cfg,
Duncan Coutts's avatar
Duncan Coutts committed
410
		    splitObjs           = split_objs,
411 412 413
		    withPackageDB       = packageDb,
                    progPrefix          = fromFlag $ configProgPrefix cfg,
                    progSuffix          = fromFlag $ configProgSuffix cfg
Duncan Coutts's avatar
Duncan Coutts committed
414
                  }
ijones's avatar
ijones committed
415

416 417 418
        let dirs = absoluteInstallDirs pkg_descr lbi NoCopyDest
            relative = prefixRelativeInstallDirs pkg_descr lbi

419 420 421
        unless (isAbsolute (prefix dirs)) $ die $
            "expected an absolute directory name for --prefix: " ++ prefix dirs

422 423
        info verbosity $ "Using compiler: " ++ showCompilerId comp
        info verbosity $ "Using install prefix: " ++ prefix dirs
424

425 426
        let dirinfo name dir isPrefixRelative =
              info verbosity $ name ++ " installed in: " ++ dir ++ relNote
427 428 429 430 431
              where relNote = case buildOS of
                      Windows | not (hasLibs pkg_descr)
                             && isNothing isPrefixRelative
                             -> "  (fixed location)"
                      _      -> ""
432

433 434 435 436 437 438 439
        dirinfo "Binaries"         (bindir dirs)     (bindir relative)
        dirinfo "Libraries"        (libdir dirs)     (libdir relative)
        dirinfo "Private binaries" (libexecdir dirs) (libexecdir relative)
        dirinfo "Data files"       (datadir dirs)    (datadir relative)
        dirinfo "Documentation"    (docdir dirs)     (docdir relative)

        sequence_ [ reportProgram verbosity prog configuredProg
440
                  | (prog, configuredProg) <- knownPrograms programsConfig''' ]
441

442
	return lbi
443

444

445 446 447
-- -----------------------------------------------------------------------------
-- Configuring package dependencies

ijones's avatar
ijones committed
448 449
-- |Converts build dependencies to a versioned dependency.  only sets
-- version information for exact versioned dependencies.
450
inventBogusPackageId :: Dependency -> PackageIdentifier
ijones's avatar
ijones committed
451 452

-- if they specify the exact version, use that:
453
inventBogusPackageId (Dependency s (ThisVersion v)) = PackageIdentifier s v
ijones's avatar
ijones committed
454 455

-- otherwise, just set it to empty
456
inventBogusPackageId (Dependency s _) = PackageIdentifier s (Version [] [])
ijones's avatar
ijones committed
457

458 459 460 461 462
reportProgram :: Verbosity -> Program -> Maybe ConfiguredProgram -> IO ()
reportProgram verbosity prog Nothing
    = info verbosity $ "No " ++ programName prog ++ " found"
reportProgram verbosity prog (Just configuredProg)
    = info verbosity $ "Using " ++ programName prog ++ version ++ location
463 464 465 466 467 468
    where location = case programLocation configuredProg of
            FoundOnSystem p -> " found on system at: " ++ p
            UserSpecified p -> " given by user at: " ++ p
          version = case programVersion configuredProg of
            Nothing -> ""
            Just v  -> " version " ++ showVersion v
ijones's avatar
ijones committed
469

470 471
hackageUrl :: String
hackageUrl = "http://hackage.haskell.org/cgi-bin/hackage-scripts/package/"
472

ijones's avatar
ijones committed
473
-- | Test for a package dependency and record the version we have installed.
474
configDependency :: Verbosity -> PackageIndex InstalledPackageInfo -> Dependency -> IO PackageIdentifier
475
configDependency verbosity index dep@(Dependency pkgname vrange) =
476 477
  case PackageIndex.lookupDependency index dep of
        [] -> die $ "cannot satisfy dependency "
Duncan Coutts's avatar
Duncan Coutts committed
478 479 480
                      ++ pkgname ++ showVersionRange vrange ++ "\n"
                      ++ "Perhaps you need to download and install it from\n"
                      ++ hackageUrl ++ pkgname ++ "?"
481
        pkgs -> do let pkgid = maximumBy (comparing packageVersion) (map packageId pkgs)
482
                   info verbosity $ "Dependency " ++ pkgname
Duncan Coutts's avatar
Duncan Coutts committed
483
                                ++ showVersionRange vrange
484 485
                                ++ ": using " ++ showPackageId pkgid
                   return pkgid
ijones's avatar
ijones committed
486

487
getInstalledPackages :: Verbosity -> Compiler -> PackageDB -> ProgramConfiguration
488
                     -> IO (Maybe (PackageIndex InstalledPackageInfo))
489
getInstalledPackages verbosity comp packageDb progconf = do
490
  info verbosity "Reading installed packages..."
491
  case compilerFlavor comp of
492
    GHC -> Just `fmap` GHC.getInstalledPackages verbosity packageDb progconf
493 494
    JHC -> Just `fmap` JHC.getInstalledPackages verbosity packageDb progconf
    _   -> return Nothing
ekarttun's avatar
ekarttun committed
495

496 497 498 499 500 501 502 503 504 505 506 507 508
-- -----------------------------------------------------------------------------
-- Configuring program dependencies

configureRequiredPrograms :: Verbosity -> [Dependency] -> ProgramConfiguration -> IO ProgramConfiguration
configureRequiredPrograms verbosity deps conf =
  foldM (configureRequiredProgram verbosity) conf deps

configureRequiredProgram :: Verbosity -> ProgramConfiguration -> Dependency -> IO ProgramConfiguration
configureRequiredProgram verbosity conf (Dependency progName verRange) =
  case lookupKnownProgram progName conf of
    Nothing -> die ("Unknown build tool " ++ show progName)
    Just prog -> snd `fmap` requireProgram verbosity prog verRange conf

509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
-- -----------------------------------------------------------------------------
-- Configuring pkg-config package dependencies

configurePkgconfigPackages :: Verbosity -> PackageDescription
                           -> ProgramConfiguration
                           -> IO (PackageDescription, ProgramConfiguration)
configurePkgconfigPackages verbosity pkg_descr conf
  | null allpkgs = return (pkg_descr, conf)
  | otherwise    = do
    (_, conf') <- requireProgram (lessVerbose verbosity) pkgConfigProgram
                    (orLaterVersion $ Version [0,9,0] []) conf
    mapM_ requirePkg allpkgs
    lib'  <- updateLibrary (library pkg_descr)
    exes' <- mapM updateExecutable (executables pkg_descr)
    let pkg_descr' = pkg_descr { library = lib', executables = exes' }
    return (pkg_descr', conf')
        
  where 
    allpkgs = concatMap pkgconfigDepends (allBuildInfo pkg_descr)
    pkgconfig = rawSystemProgramStdoutConf (lessVerbose verbosity)
                  pkgConfigProgram conf

    requirePkg (Dependency pkg range) = do
      version <- pkgconfig ["--modversion", pkg]
                 `Exception.catch` \_ -> die notFound
      case readVersion version of
        Nothing -> die "parsing output of pkg-config --modversion failed"
        Just v | not (withinRange v range) -> die (badVersion v)
537
               | otherwise                 -> info verbosity (depSatisfied v)
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
      where 
        notFound     = "The pkg-config package " ++ pkg ++ versionRequirement
                    ++ " is required but it could not be found."
        badVersion v = "The pkg-config package " ++ pkg ++ versionRequirement
                    ++ " is required but the version installed on the"
                    ++ " system is version " ++ showVersion v
        depSatisfied v = "Dependency " ++ pkg ++ showVersionRange range
                      ++ ": using version " ++ showVersion v

        versionRequirement
          | range == AnyVersion = ""
          | otherwise           = " version " ++ showVersionRange range                            

    updateLibrary Nothing    = return Nothing
    updateLibrary (Just lib) = do
553
      bi <- pkgconfigBuildInfo (pkgconfigDepends (libBuildInfo lib))
554
      return $ Just lib { libBuildInfo = libBuildInfo lib `mappend` bi }
555 556

    updateExecutable exe = do
557
      bi <- pkgconfigBuildInfo (pkgconfigDepends (buildInfo exe))
558
      return exe { buildInfo = buildInfo exe `mappend` bi }
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581

    pkgconfigBuildInfo :: [Dependency] -> IO BuildInfo
    pkgconfigBuildInfo pkgdeps = do
      let pkgs = nub [ pkg | Dependency pkg _ <- pkgdeps ]
      ccflags <- pkgconfig ("--cflags" : pkgs)
      ldflags <- pkgconfig ("--libs"   : pkgs)
      return (ccLdOptionsBuildInfo (words ccflags) (words ldflags))

-- | Makes a 'BuildInfo' from C compiler and linker flags.
--
-- This can be used with the output from configuration programs like pkg-config
-- and similar package-specific programs like mysql-config, freealut-config etc.
-- For example:
--
-- > ccflags <- rawSystemProgramStdoutConf verbosity prog conf ["--cflags"]
-- > ldflags <- rawSystemProgramStdoutConf verbosity prog conf ["--libs"]
-- > return (ccldOptionsBuildInfo (words ccflags) (words ldflags))
--
ccLdOptionsBuildInfo :: [String] -> [String] -> BuildInfo
ccLdOptionsBuildInfo cflags ldflags =
  let (includeDirs',  cflags')   = partition ("-I" `isPrefixOf`) cflags
      (extraLibs',    ldflags')  = partition ("-l" `isPrefixOf`) ldflags
      (extraLibDirs', ldflags'') = partition ("-L" `isPrefixOf`) ldflags'
582
  in mempty {
583 584 585 586 587
       PD.includeDirs  = map (drop 2) includeDirs',
       PD.extraLibs    = map (drop 2) extraLibs',
       PD.extraLibDirs = map (drop 2) extraLibDirs',
       PD.ccOptions    = cflags',
       PD.ldOptions    = ldflags''
588
     }
589

590 591 592
-- -----------------------------------------------------------------------------
-- Determining the compiler details

593
configCompilerAux :: ConfigFlags -> IO (Compiler, ProgramConfiguration)
594 595 596
configCompilerAux cfg = configCompiler (flagToMaybe $ configHcFlavor cfg)
                                       (flagToMaybe $ configHcPath cfg)
                                       (flagToMaybe $ configHcPkg cfg)
Duncan Coutts's avatar
Duncan Coutts committed
597
                                       defaultProgramConfiguration
598
                                       (fromFlag (configVerbose cfg))
599

600
configCompiler :: Maybe CompilerFlavor -> Maybe FilePath -> Maybe FilePath
601 602 603 604 605 606 607 608 609
               -> ProgramConfiguration -> Verbosity
               -> IO (Compiler, ProgramConfiguration)
configCompiler Nothing _ _ _ _ = die "Unknown compiler"
configCompiler (Just hcFlavor) hcPath hcPkg conf verbosity = do
  case hcFlavor of
      GHC  -> GHC.configure  verbosity hcPath hcPkg conf
      JHC  -> JHC.configure  verbosity hcPath hcPkg conf
      Hugs -> Hugs.configure verbosity hcPath hcPkg conf
      NHC  -> NHC.configure  verbosity hcPath hcPkg conf
610
      _    -> die "Unknown compiler"
ekarttun's avatar
ekarttun committed
611

612

613 614 615 616 617 618 619 620 621 622 623
-- | Output package check warnings and errors. Exit if any errors.
checkPackageProblems :: Verbosity -> PackageDescription -> IO ()
checkPackageProblems verbosity pkg_descr = do
  ioChecks      <- checkPackageFiles pkg_descr "."
  let pureChecks = checkPackage      pkg_descr
      errors   = [ e | PackageBuildImpossible e <- pureChecks ++ ioChecks ]
      warnings = [ w | PackageBuildWarning    w <- pureChecks ++ ioChecks ]
  if null errors
    then mapM_ (warn verbosity) warnings
    else do mapM_ (hPutStrLn stderr . ("Error: " ++)) errors
            exitWith (ExitFailure 1)
624

625
-- -----------------------------------------------------------------------------
626
-- Tests
627

628
{- Too specific:
629
hunitTests :: [Test]
simonmar's avatar
simonmar committed
630
hunitTests = []
ijones's avatar
ijones committed
631
packageID = PackageIdentifier "Foo" (Version [1] [])
632
    = [TestCase $
ijones's avatar
ijones committed
633 634 635
       do let simonMarGHCLoc = "/usr/bin/ghc"
          simonMarGHC <- configure emptyPackageDescription {package=packageID}
                                       (Just GHC,
636
				       Just simonMarGHCLoc,
ijones's avatar
ijones committed
637
				       Nothing, Nothing)
638
	  assertEqual "finding ghc, etc on simonMar's machine failed"
639
             (LocalBuildInfo "/usr" (Compiler GHC 
simonmar's avatar
simonmar committed
640
	                    (Version [6,2,2] []) simonMarGHCLoc 
ijones's avatar
ijones committed
641
 			    (simonMarGHCLoc ++ "-pkg")) [] [])
642 643
             simonMarGHC
      ]
simonmar's avatar
simonmar committed
644
-}