Configure.hs 28.9 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,
jpbernardy's avatar
jpbernardy committed
54
                                      tryGetConfigStateFile,
ijones's avatar
ijones committed
55
                                     )
ijones's avatar
ijones committed
56
    where
57

58
import Distribution.Simple.Compiler
59
60
    ( CompilerFlavor(..), Compiler, compilerFlavor, compilerVersion
    , showCompilerId, unsupportedExtensions, PackageDB(..) )
61
import Distribution.Package
62
    ( PackageIdentifier(PackageIdentifier), packageVersion, Package(..)
63
    , Dependency(Dependency) )
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
import Distribution.Simple.Program
79
    ( Program(..), ProgramLocation(..), ConfiguredProgram(..)
Duncan Coutts's avatar
Duncan Coutts committed
80
81
    , ProgramConfiguration, defaultProgramConfiguration
    , configureAllKnownPrograms, knownPrograms
82
    , userSpecifyArgs, userSpecifyPath
83
84
    , lookupKnownProgram, requireProgram, pkgConfigProgram
    , rawSystemProgramStdoutConf )
85
import Distribution.Simple.Setup
86
    ( ConfigFlags(..), CopyDest(..), fromFlag, fromFlagOrDefault, flagToMaybe )
87
import Distribution.Simple.InstallDirs
88
    ( InstallDirs(..), defaultInstallDirs, combineInstallDirs )
89
import Distribution.Simple.LocalBuildInfo
90
    ( LocalBuildInfo(..), absoluteInstallDirs
91
    , prefixRelativeInstallDirs )
92
93
import Distribution.Simple.BuildPaths
    ( distPref )
94
import Distribution.Simple.Utils
95
    ( die, warn, info, setupMessage, createDirectoryIfMissingVerbose
96
    , intercalate, comparing, cabalVersion, cabalBootstrapping )
97
98
99
import Distribution.Simple.Register
    ( removeInstalledConfig )
import Distribution.System
100
    ( OS(..), buildOS, buildArch )
101
import Distribution.Version
102
    ( Version(..), VersionRange(..), orLaterVersion, withinRange )
103
import Distribution.Verbosity
104
    ( Verbosity, lessVerbose )
105

106
107
108
109
110
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

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

138
139
tryGetConfigStateFile :: (Read a) => FilePath -> IO (Either String a)
tryGetConfigStateFile filename = do
140
141
142
  exists <- doesFileExist filename
  if not exists
    then return (Left missing)
143
144
    else do
      str <- readFileStrict filename
145
146
147
148
149
150
151
152
      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
153
154
155
156
157
    readFileStrict name = do 
      h <- openFile name ReadMode
      str <- hGetContents h >>= \str -> length str `seq` return str 
      hClose h
      return str
158
159
160
161
162
163
164
165
166
167
168
169
170
171
    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 "
172
173
             ++ display cabalId ++ ", now "
             ++ display currentCabalId ++ ")."
174
175
176
177
             ++ badcompiler compilerId
    badcompiler compilerId | compilerId == currentCompilerId = ""
                           | otherwise
              = " Additionally the compiler is different (was "
178
179
             ++ display compilerId ++ ", now "
             ++ display currentCompilerId
180
             ++ ") which is probably the cause of the problem."
181

182
183
184
185
-- internal function
tryGetPersistBuildConfig :: IO (Either String LocalBuildInfo)
tryGetPersistBuildConfig = tryGetConfigStateFile localBuildInfoFile

186
187
188
-- |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.
189
190
191
192
193
getPersistBuildConfig :: IO LocalBuildInfo
getPersistBuildConfig = do
  lbi <- tryGetPersistBuildConfig
  either die return lbi

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

ijones's avatar
ijones committed
200
201
-- |After running configure, output the 'LocalBuildInfo' to the
-- 'localBuildInfoFile'.
ijones's avatar
ijones committed
202
writePersistBuildConfig :: LocalBuildInfo -> IO ()
203
writePersistBuildConfig lbi = do
Ross Paterson's avatar
Ross Paterson committed
204
  createDirectoryIfMissing False distPref
205
206
207
208
209
210
211
  writeFile localBuildInfoFile $ showHeader pkgid
                              ++ '\n' : show lbi
  where
    pkgid   = packageId (localPkgDescr lbi)

showHeader :: PackageIdentifier -> String
showHeader pkgid =
212
213
214
     "Saved package config for " ++ display pkgid
  ++ " written by " ++ display currentCabalId
  ++      " using " ++ display currentCompilerId
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
  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]
230
231
232
    -> case (simpleParse pkgid :: Maybe PackageIdentifier,
             simpleParse cabalid,
             simpleParse compilerid) of
233
234
235
236
237
        (Just _,
         Just cabalid',
         Just compilerid') -> Just (cabalid', compilerid')
        _                  -> Nothing
  _                        -> Nothing
238

239
240
241
242
243
244
245
246
247
-- |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
248
-- |@dist\/setup-config@
249
localBuildInfoFile :: FilePath
Ross Paterson's avatar
Ross Paterson committed
250
localBuildInfoFile = distPref </> "setup-config"
ijones's avatar
ijones committed
251

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

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

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

267
	createDirectoryIfMissingVerbose (lessVerbose verbosity) True distPref
268

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

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

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

291
        (pkg_descr0', flags) <- case pkg_descr0 of
292
293
294
            Left ppd -> 
                case finalizePackageDescription 
                       (configConfigurationsFlags cfg)
295
                       maybePackageIndex
296
                       Distribution.System.buildOS
297
                       Distribution.System.buildArch
298
                       (flavor, version)
299
                       (configConstraints cfg)
300
301
302
303
304
                       ppd
                of Right r -> return r
                   Left missing -> 
                       die $ "At least the following dependencies are missing:\n"
                         ++ (render . nest 4 . sep . punctuate comma $ 
305
                             map disp missing)
306
307
            Right pd -> return (pd,[])
              
308
309
310
        -- add extra include/lib dirs as specified in cfg
        -- we do it here so that those get checked too
        let pkg_descr = addExtraIncludeLibDirs pkg_descr0'
311

312
        when (not (null flags)) $
313
          info verbosity $ "Flags chosen: " ++ (intercalate ", " .
314
315
                      map (\(n,b) -> n ++ "=" ++ show b) $ flags)

316
        checkPackageProblems verbosity (updatePackageDescription pbi pkg_descr)
317

318
319
320
321
322
323
324
325
326
327
328
329
330
331
        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 ]
332
        dep_pkgs <- case flavor of
333
334
          GHC -> mapM (configDependency verbosity packageIndex) (buildDepends pkg_descr)
          JHC -> mapM (configDependency verbosity packageIndex) (buildDepends pkg_descr)
335
          _   -> return bogusDependencies
Simon Marlow's avatar
Simon Marlow committed
336

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

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

	removeInstalledConfig

367
	-- installation directories
368
	defaultDirs <- defaultInstallDirs flavor userInstall (hasLibs pkg_descr)
369
370
	let installDirs = combineInstallDirs fromFlagOrDefault
                            defaultDirs (configInstallDirs cfg)
371

372
        -- check extensions
373
        let extlist = nub $ concatMap extensions (allBuildInfo pkg_descr)
374
        let exts = unsupportedExtensions comp extlist
375
        unless (null exts) $ warn verbosity $ -- Just warn, FIXME: Should this be an error?
376
            display flavor ++ " does not support the following extensions: " ++
377
            intercalate ", " (map display exts)
378

379
        let requiredBuildTools = concatMap buildTools (allBuildInfo pkg_descr)
380
381
        programsConfig'' <-
              configureAllKnownPrograms (lessVerbose verbosity) programsConfig'
382
          >>= configureRequiredPrograms verbosity requiredBuildTools
383
        
384
385
        (pkg_descr', programsConfig''') <- configurePkgconfigPackages verbosity
                                            pkg_descr programsConfig''
386

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

397
	let lbi = LocalBuildInfo{
398
399
		    installDirTemplates = installDirs,
		    compiler            = comp,
Duncan Coutts's avatar
Duncan Coutts committed
400
		    buildDir            = distPref </> "build",
401
402
403
		    scratchDir          = fromFlagOrDefault
                                            (distPref </> "scratch")
                                            (configScratchDir cfg),
404
		    packageDeps         = dep_pkgs,
405
                    installedPkgs       = packageDependsIndex,
406
                    pkgDescrFile        = Nothing,
407
		    localPkgDescr       = pkg_descr',
408
409
410
411
412
413
414
		    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
415
		    splitObjs           = split_objs,
416
                    stripExes           = fromFlag $ configStripExes cfg,
417
418
419
		    withPackageDB       = packageDb,
                    progPrefix          = fromFlag $ configProgPrefix cfg,
                    progSuffix          = fromFlag $ configProgSuffix cfg
Duncan Coutts's avatar
Duncan Coutts committed
420
                  }
ijones's avatar
ijones committed
421

422
423
424
        let dirs = absoluteInstallDirs pkg_descr lbi NoCopyDest
            relative = prefixRelativeInstallDirs pkg_descr lbi

425
426
427
        unless (isAbsolute (prefix dirs)) $ die $
            "expected an absolute directory name for --prefix: " ++ prefix dirs

428
429
        info verbosity $ "Using compiler: " ++ showCompilerId comp
        info verbosity $ "Using install prefix: " ++ prefix dirs
430

431
432
        let dirinfo name dir isPrefixRelative =
              info verbosity $ name ++ " installed in: " ++ dir ++ relNote
433
434
435
436
437
              where relNote = case buildOS of
                      Windows | not (hasLibs pkg_descr)
                             && isNothing isPrefixRelative
                             -> "  (fixed location)"
                      _      -> ""
438

439
440
441
442
443
444
445
        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
446
                  | (prog, configuredProg) <- knownPrograms programsConfig''' ]
447

448
	return lbi
449

450
451
452
    where
      addExtraIncludeLibDirs pkg_descr =
          let extraBi = mempty { extraLibDirs = configExtraLibDirs cfg
Malcolm.Wallace's avatar
Malcolm.Wallace committed
453
                               , PD.includeDirs = configExtraIncludeDirs cfg}
454
455
456
457
              modifyLib l        = l{ libBuildInfo = libBuildInfo l `mappend` extraBi }
              modifyExecutable e = e{ buildInfo    = buildInfo e    `mappend` extraBi}
          in pkg_descr{ library     = modifyLib        `fmap` library pkg_descr
                      , executables = modifyExecutable  `map` executables pkg_descr}
458
459
460
-- -----------------------------------------------------------------------------
-- Configuring package dependencies

ijones's avatar
ijones committed
461
462
-- |Converts build dependencies to a versioned dependency.  only sets
-- version information for exact versioned dependencies.
463
inventBogusPackageId :: Dependency -> PackageIdentifier
ijones's avatar
ijones committed
464
465

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

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

471
472
473
474
475
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
476
477
478
479
480
    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 -> ""
481
            Just v  -> " version " ++ display v
ijones's avatar
ijones committed
482

483
484
hackageUrl :: String
hackageUrl = "http://hackage.haskell.org/cgi-bin/hackage-scripts/package/"
485

ijones's avatar
ijones committed
486
-- | Test for a package dependency and record the version we have installed.
487
configDependency :: Verbosity -> PackageIndex InstalledPackageInfo -> Dependency -> IO PackageIdentifier
488
configDependency verbosity index dep@(Dependency pkgname vrange) =
489
490
  case PackageIndex.lookupDependency index dep of
        [] -> die $ "cannot satisfy dependency "
491
                      ++ pkgname ++ display vrange ++ "\n"
Duncan Coutts's avatar
Duncan Coutts committed
492
493
                      ++ "Perhaps you need to download and install it from\n"
                      ++ hackageUrl ++ pkgname ++ "?"
494
        pkgs -> do let pkgid = maximumBy (comparing packageVersion) (map packageId pkgs)
495
                   info verbosity $ "Dependency " ++ pkgname
496
                                ++ display vrange
497
                                ++ ": using " ++ display pkgid
498
                   return pkgid
ijones's avatar
ijones committed
499

500
getInstalledPackages :: Verbosity -> Compiler -> PackageDB -> ProgramConfiguration
501
                     -> IO (Maybe (PackageIndex InstalledPackageInfo))
502
getInstalledPackages verbosity comp packageDb progconf = do
503
  info verbosity "Reading installed packages..."
504
  case compilerFlavor comp of
505
    GHC -> Just `fmap` GHC.getInstalledPackages verbosity packageDb progconf
506
507
    JHC -> Just `fmap` JHC.getInstalledPackages verbosity packageDb progconf
    _   -> return Nothing
ekarttun's avatar
ekarttun committed
508

509
510
511
512
513
514
515
516
517
518
519
520
521
-- -----------------------------------------------------------------------------
-- 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

522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
-- -----------------------------------------------------------------------------
-- 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
547
      case simpleParse version of
548
549
        Nothing -> die "parsing output of pkg-config --modversion failed"
        Just v | not (withinRange v range) -> die (badVersion v)
550
               | otherwise                 -> info verbosity (depSatisfied v)
551
552
553
554
555
      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"
556
557
558
                    ++ " system is version " ++ display v
        depSatisfied v = "Dependency " ++ pkg ++ display range
                      ++ ": using version " ++ display v
559
560
561

        versionRequirement
          | range == AnyVersion = ""
562
          | otherwise           = " version " ++ display range
563
564
565

    updateLibrary Nothing    = return Nothing
    updateLibrary (Just lib) = do
566
      bi <- pkgconfigBuildInfo (pkgconfigDepends (libBuildInfo lib))
567
      return $ Just lib { libBuildInfo = libBuildInfo lib `mappend` bi }
568
569

    updateExecutable exe = do
570
      bi <- pkgconfigBuildInfo (pkgconfigDepends (buildInfo exe))
571
      return exe { buildInfo = buildInfo exe `mappend` bi }
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594

    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'
595
  in mempty {
596
597
598
599
600
       PD.includeDirs  = map (drop 2) includeDirs',
       PD.extraLibs    = map (drop 2) extraLibs',
       PD.extraLibDirs = map (drop 2) extraLibDirs',
       PD.ccOptions    = cflags',
       PD.ldOptions    = ldflags''
601
     }
602

603
604
605
-- -----------------------------------------------------------------------------
-- Determining the compiler details

606
configCompilerAux :: ConfigFlags -> IO (Compiler, ProgramConfiguration)
607
608
609
configCompilerAux cfg = configCompiler (flagToMaybe $ configHcFlavor cfg)
                                       (flagToMaybe $ configHcPath cfg)
                                       (flagToMaybe $ configHcPkg cfg)
Duncan Coutts's avatar
Duncan Coutts committed
610
                                       defaultProgramConfiguration
611
                                       (fromFlag (configVerbosity cfg))
612

613
configCompiler :: Maybe CompilerFlavor -> Maybe FilePath -> Maybe FilePath
614
615
616
617
618
619
620
621
622
               -> 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
623
      _    -> die "Unknown compiler"
ekarttun's avatar
ekarttun committed
624

625

626
627
628
629
630
631
632
633
634
635
636
-- | 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)
637

638
-- -----------------------------------------------------------------------------
639
-- Tests
640

641
{- Too specific:
642
hunitTests :: [Test]
simonmar's avatar
simonmar committed
643
hunitTests = []
ijones's avatar
ijones committed
644
packageID = PackageIdentifier "Foo" (Version [1] [])
645
    = [TestCase $
ijones's avatar
ijones committed
646
647
648
       do let simonMarGHCLoc = "/usr/bin/ghc"
          simonMarGHC <- configure emptyPackageDescription {package=packageID}
                                       (Just GHC,
649
				       Just simonMarGHCLoc,
ijones's avatar
ijones committed
650
				       Nothing, Nothing)
651
	  assertEqual "finding ghc, etc on simonMar's machine failed"
652
             (LocalBuildInfo "/usr" (Compiler GHC 
simonmar's avatar
simonmar committed
653
	                    (Version [6,2,2] []) simonMarGHCLoc 
ijones's avatar
ijones committed
654
 			    (simonMarGHCLoc ++ "-pkg")) [] [])
655
656
             simonMarGHC
      ]
simonmar's avatar
simonmar committed
657
-}