Simple.hs 30.6 KB
Newer Older
1
2
3
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RankNTypes #-}

4
5
-----------------------------------------------------------------------------
-- |
ijones's avatar
ijones committed
6
-- Module      :  Distribution.Simple
ijones's avatar
ijones committed
7
-- Copyright   :  Isaac Jones 2003-2005
8
-- License     :  BSD3
9
--
Duncan Coutts's avatar
Duncan Coutts committed
10
-- Maintainer  :  cabal-devel@haskell.org
11
-- Portability :  portable
12
--
Duncan Coutts's avatar
Duncan Coutts committed
13
14
15
16
17
18
19
20
21
-- This is the command line front end to the Simple build system. When given
-- the parsed command-line args and package information, is able to perform
-- basic commands like configure, build, install, register, etc.
--
-- This module exports the main functions that Setup.hs scripts use. It
-- re-exports the 'UserHooks' type, the standard entry points like
-- 'defaultMain' and 'defaultMainWithHooks' and the predefined sets of
-- 'UserHooks' that custom @Setup.hs@ scripts can extend to add their own
-- behaviour.
22
--
ijones's avatar
ijones committed
23
24
-- This module isn't called \"Simple\" because it's simple.  Far from
-- it.  It's called \"Simple\" because it does complicated things to
25
-- simple software.
Duncan Coutts's avatar
Duncan Coutts committed
26
27
28
29
--
-- The original idea was that there could be different build systems that all
-- presented the same compatible command line interfaces. There is still a
-- "Distribution.Make" system but in practice no packages use it.
30

31
32
33
34
35
36
37
38
39
{-
Work around this warning:
libraries/Cabal/Distribution/Simple.hs:78:0:
    Warning: In the use of `runTests'
             (imported from Distribution.Simple.UserHooks):
             Deprecated: "Please use the new testing interface instead!"
-}
{-# OPTIONS_GHC -fno-warn-deprecations #-}

40
module Distribution.Simple (
41
42
43
44
45
        module Distribution.Package,
        module Distribution.Version,
        module Distribution.License,
        module Distribution.Simple.Compiler,
        module Language.Haskell.Extension,
46
        -- * Simple interface
47
        defaultMain, defaultMainNoRead, defaultMainArgs,
48
49
        -- * Customization
        UserHooks(..), Args,
50
51
        defaultMainWithHooks, defaultMainWithHooksArgs,
        defaultMainWithHooksNoRead,
52
        -- ** Standard sets of hooks
53
54
55
56
        simpleUserHooks,
        autoconfUserHooks,
        defaultUserHooks, emptyUserHooks,
        -- ** Utils
57
        defaultHookedPackageDesc
58
  ) where
59

60
61
62
import Prelude ()
import Distribution.Compat.Prelude

ijones's avatar
ijones committed
63
-- local
64
import Distribution.Simple.Compiler hiding (Flag)
65
import Distribution.Simple.UserHooks
66
67
import Distribution.Package
import Distribution.PackageDescription hiding (Flag)
68
69
import Distribution.PackageDescription.Parse
import Distribution.PackageDescription.Configuration
70
import Distribution.Simple.Program
71
import Distribution.Simple.Program.Db
72
import Distribution.Simple.PreProcess
73
import Distribution.Simple.Setup
74
import Distribution.Simple.Command
75

76
77
import Distribution.Simple.Build
import Distribution.Simple.SrcDist
78
import Distribution.Simple.Register
79

80
import Distribution.Simple.Configure
81
82
83
84
85
86
87

import Distribution.Simple.LocalBuildInfo
import Distribution.Simple.Bench
import Distribution.Simple.BuildPaths
import Distribution.Simple.Test
import Distribution.Simple.Install
import Distribution.Simple.Haddock
88
import Distribution.Simple.Utils
89
import Distribution.Utils.NubList
90
import Distribution.Verbosity
ijones's avatar
ijones committed
91
import Language.Haskell.Extension
92
93
import Distribution.Version
import Distribution.License
94
import Distribution.Text
95

ijones's avatar
ijones committed
96
-- Base
97
98
99
100
101
102
103
import System.Environment (getArgs, getProgName)
import System.Directory   (removeFile, doesFileExist
                          ,doesDirectoryExist, removeDirectoryRecursive)
import System.Exit                          (exitWith,ExitCode(..))
import System.FilePath                      (searchPathSeparator)
import Distribution.Compat.Environment      (getEnvironment)
import Distribution.Compat.GetShortPathName (getShortPathName)
ijones's avatar
ijones committed
104

105
import Data.List       (unionBy, (\\))
106

Simon Marlow's avatar
Simon Marlow committed
107
-- | A simple implementation of @main@ for a Cabal setup script.
108
109
-- It reads the package description file using IO, and performs the
-- action specified on the command line.
110
defaultMain :: IO ()
111
defaultMain = getArgs >>= defaultMainHelper simpleUserHooks
112

Simon Marlow's avatar
Simon Marlow committed
113
114
-- | A version of 'defaultMain' that is passed the command line
-- arguments, rather than getting them from the environment.
115
defaultMainArgs :: [String] -> IO ()
116
defaultMainArgs = defaultMainHelper simpleUserHooks
ijones's avatar
ijones committed
117

118
-- | A customizable version of 'defaultMain'.
ijones's avatar
ijones committed
119
defaultMainWithHooks :: UserHooks -> IO ()
120
defaultMainWithHooks hooks = getArgs >>= defaultMainHelper hooks
121

Simon Marlow's avatar
Simon Marlow committed
122
123
-- | A customizable version of 'defaultMain' that also takes the command
-- line arguments.
124
defaultMainWithHooksArgs :: UserHooks -> [String] -> IO ()
125
defaultMainWithHooksArgs = defaultMainHelper
Simon Marlow's avatar
Simon Marlow committed
126
127

-- | Like 'defaultMain', but accepts the package description as input
128
-- rather than using IO to read it.
129
defaultMainNoRead :: GenericPackageDescription -> IO ()
130
131
132
133
134
defaultMainNoRead = defaultMainWithHooksNoRead simpleUserHooks

-- | A customizable version of 'defaultMainNoRead'.
defaultMainWithHooksNoRead :: UserHooks -> GenericPackageDescription -> IO ()
defaultMainWithHooksNoRead hooks pkg_descr =
135
  getArgs >>=
136
  defaultMainHelper hooks { readDesc = return (Just pkg_descr) }
137

138
defaultMainHelper :: UserHooks -> Args -> IO ()
139
defaultMainHelper hooks args = topHandler $
140
  case commandsRun (globalCommand commands) commands args of
141
    CommandHelp   help                 -> printHelp help
142
    CommandList   opts                 -> printOptionsList opts
143
144
145
    CommandErrors errs                 -> printErrors errs
    CommandReadyToGo (flags, commandParse)  ->
      case commandParse of
146
147
        _ | fromFlag (globalVersion flags)        -> printVersion
          | fromFlag (globalNumericVersion flags) -> printNumericVersion
148
        CommandHelp     help           -> printHelp help
149
        CommandList     opts           -> printOptionsList opts
150
151
152
153
154
        CommandErrors   errs           -> printErrors errs
        CommandReadyToGo action        -> action

  where
    printHelp help = getProgName >>= putStr . help
155
    printOptionsList = putStr . unlines
156
    printErrors errs = do
157
      putStr (intercalate "\n" errs)
158
      exitWith (ExitFailure 1)
159
    printNumericVersion = putStrLn $ display cabalVersion
160
    printVersion        = putStrLn $ "Cabal library version "
161
                                  ++ display cabalVersion
162

163
    progs = addKnownPrograms (hookedPrograms hooks) defaultProgramDb
164
    commands =
165
166
      [configureCommand progs `commandAddAction`
        \fs as -> configureAction hooks fs as >> return ()
167
      ,buildCommand     progs `commandAddAction` buildAction        hooks
168
      ,replCommand      progs `commandAddAction` replAction         hooks
169
170
171
172
173
174
175
176
177
      ,installCommand         `commandAddAction` installAction      hooks
      ,copyCommand            `commandAddAction` copyAction         hooks
      ,haddockCommand         `commandAddAction` haddockAction      hooks
      ,cleanCommand           `commandAddAction` cleanAction        hooks
      ,sdistCommand           `commandAddAction` sdistAction        hooks
      ,hscolourCommand        `commandAddAction` hscolourAction     hooks
      ,registerCommand        `commandAddAction` registerAction     hooks
      ,unregisterCommand      `commandAddAction` unregisterAction   hooks
      ,testCommand            `commandAddAction` testAction         hooks
tibbe's avatar
tibbe committed
178
      ,benchmarkCommand       `commandAddAction` benchAction        hooks
179
      ]
Simon Marlow's avatar
Simon Marlow committed
180
181

-- | Combine the preprocessors in the given hooks with the
182
-- preprocessors built into cabal.
183
allSuffixHandlers :: UserHooks
184
185
                  -> [PPSuffixHandler]
allSuffixHandlers hooks
186
    = overridesPP (hookedPreProcessors hooks) knownSuffixHandlers
187
188
189
190
    where
      overridesPP :: [PPSuffixHandler] -> [PPSuffixHandler] -> [PPSuffixHandler]
      overridesPP = unionBy (\x y -> fst x == fst y)

191
configureAction :: UserHooks -> ConfigFlags -> Args -> IO LocalBuildInfo
192
configureAction hooks flags args = do
193
    distPref <- findDistPrefOrDefault (configDistPref flags)
194
195
    let flags' = flags { configDistPref = toFlag distPref
                       , configArgs = args }
196
197

    -- See docs for 'HookedBuildInfo'
198
199
    pbi <- preConf hooks args flags'

200
    (mb_pd_file, pkg_descr0) <- confPkgDescr hooks verbosity
201
                                    (flagToMaybe (configCabalFilePath flags))
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219

    let epkg_descr = (pkg_descr0, pbi)

    localbuildinfo0 <- confHook hooks epkg_descr flags'

    -- remember the .cabal filename if we know it
    -- and all the extra command line args
    let localbuildinfo = localbuildinfo0 {
                           pkgDescrFile = mb_pd_file,
                           extraConfigArgs = args
                         }
    writePersistBuildConfig distPref localbuildinfo

    let pkg_descr = localPkgDescr localbuildinfo
    postConf hooks args flags' pkg_descr localbuildinfo
    return localbuildinfo
  where
    verbosity = fromFlag (configVerbosity flags)
220

221
222
confPkgDescr :: UserHooks -> Verbosity -> Maybe FilePath
             -> IO (Maybe FilePath, GenericPackageDescription)
223
confPkgDescr hooks verbosity mb_path = do
224
225
226
227
  mdescr <- readDesc hooks
  case mdescr of
    Just descr -> return (Nothing, descr)
    Nothing -> do
228
229
230
        pdfile <- case mb_path of
                    Nothing -> defaultPackageDesc verbosity
                    Just path -> return path
231
232
        descr  <- readPackageDescription verbosity pdfile
        return (Just pdfile, descr)
Simon Marlow's avatar
Simon Marlow committed
233

234
235
buildAction :: UserHooks -> BuildFlags -> Args -> IO ()
buildAction hooks flags args = do
236
237
238
  distPref <- findDistPrefOrDefault (buildDistPref flags)
  let verbosity = fromFlag $ buildVerbosity flags
      flags' = flags { buildDistPref = toFlag distPref }
239

240
  lbi <- getBuildConfig hooks verbosity distPref
241
  progs <- reconfigurePrograms verbosity
242
243
             (buildProgramPaths flags')
             (buildProgramArgs flags')
244
245
246
247
             (withPrograms lbi)

  hookedAction preBuild buildHook postBuild
               (return lbi { withPrograms = progs })
248
               hooks flags' { buildArgs = args } args
249

250
251
replAction :: UserHooks -> ReplFlags -> Args -> IO ()
replAction hooks flags args = do
252
253
254
  distPref <- findDistPrefOrDefault (replDistPref flags)
  let verbosity = fromFlag $ replVerbosity flags
      flags' = flags { replDistPref = toFlag distPref }
255
256
257

  lbi <- getBuildConfig hooks verbosity distPref
  progs <- reconfigurePrograms verbosity
258
259
             (replProgramPaths flags')
             (replProgramArgs flags')
260
261
             (withPrograms lbi)

262
263
264
  -- As far as I can tell, the only reason this doesn't use
  -- 'hookedActionWithArgs' is because the arguments of 'replHook'
  -- takes the args explicitly.  UGH.   -- ezyang
265
  pbi <- preRepl hooks args flags'
266
267
268
269
270
  let pkg_descr0 = localPkgDescr lbi
  sanityCheckHookedBuildInfo pkg_descr0 pbi
  let pkg_descr = updatePackageDescription pbi pkg_descr0
      lbi' = lbi { withPrograms = progs
                 , localPkgDescr = pkg_descr }
271
272
  replHook hooks pkg_descr lbi' hooks flags' args
  postRepl hooks args flags' pkg_descr lbi'
273

274
hscolourAction :: UserHooks -> HscolourFlags -> Args -> IO ()
275
276
277
278
279
280
281
hscolourAction hooks flags args = do
    distPref <- findDistPrefOrDefault (hscolourDistPref flags)
    let verbosity = fromFlag $ hscolourVerbosity flags
        flags' = flags { hscolourDistPref = toFlag distPref }
    hookedAction preHscolour hscolourHook postHscolour
                 (getBuildConfig hooks verbosity distPref)
                 hooks flags' args
282

283
haddockAction :: UserHooks -> HaddockFlags -> Args -> IO ()
284
haddockAction hooks flags args = do
285
286
287
  distPref <- findDistPrefOrDefault (haddockDistPref flags)
  let verbosity = fromFlag $ haddockVerbosity flags
      flags' = flags { haddockDistPref = toFlag distPref }
288

289
  lbi <- getBuildConfig hooks verbosity distPref
290
  progs <- reconfigurePrograms verbosity
291
292
             (haddockProgramPaths flags')
             (haddockProgramArgs flags')
293
294
295
296
             (withPrograms lbi)

  hookedAction preHaddock haddockHook postHaddock
               (return lbi { withPrograms = progs })
297
               hooks flags' args
ijones's avatar
ijones committed
298

299
300
cleanAction :: UserHooks -> CleanFlags -> Args -> IO ()
cleanAction hooks flags args = do
301
302
303
304
    distPref <- findDistPrefOrDefault (cleanDistPref flags)
    let flags' = flags { cleanDistPref = toFlag distPref }

    pbi <- preClean hooks args flags'
305

306
    (_, ppd) <- confPkgDescr hooks verbosity Nothing
307
308
309
310
311
312
    -- It might seem like we are doing something clever here
    -- but we're really not: if you look at the implementation
    -- of 'clean' in the end all the package description is
    -- used for is to clear out @extra-tmp-files@.  IMO,
    -- the configure script goo should go into @dist@ too!
    --          -- ezyang
313
314
315
316
317
    let pkg_descr0 = flattenPackageDescription ppd
    -- We don't sanity check for clean as an error
    -- here would prevent cleaning:
    --sanityCheckHookedBuildInfo pkg_descr0 pbi
    let pkg_descr = updatePackageDescription pbi pkg_descr0
318

319
320
321
322
    cleanHook hooks pkg_descr () hooks flags'
    postClean hooks args flags' pkg_descr ()
  where
    verbosity = fromFlag (cleanVerbosity flags)
ijones's avatar
ijones committed
323

324
copyAction :: UserHooks -> CopyFlags -> Args -> IO ()
325
326
327
328
329
330
copyAction hooks flags args = do
    distPref <- findDistPrefOrDefault (copyDistPref flags)
    let verbosity = fromFlag $ copyVerbosity flags
        flags' = flags { copyDistPref = toFlag distPref }
    hookedAction preCopy copyHook postCopy
                 (getBuildConfig hooks verbosity distPref)
331
                 hooks flags' { copyArgs = args } args
332

333
installAction :: UserHooks -> InstallFlags -> Args -> IO ()
334
335
336
337
338
339
340
installAction hooks flags args = do
    distPref <- findDistPrefOrDefault (installDistPref flags)
    let verbosity = fromFlag $ installVerbosity flags
        flags' = flags { installDistPref = toFlag distPref }
    hookedAction preInst instHook postInst
                 (getBuildConfig hooks verbosity distPref)
                 hooks flags' args
341

342
343
sdistAction :: UserHooks -> SDistFlags -> Args -> IO ()
sdistAction hooks flags args = do
344
345
346
347
348
    distPref <- findDistPrefOrDefault (sDistDistPref flags)
    let flags' = flags { sDistDistPref = toFlag distPref }
    pbi <- preSDist hooks args flags'

    mlbi <- maybeGetPersistBuildConfig distPref
349

350
351
352
353
354
355
356
357
358
359
360
361
    -- NB: It would be TOTALLY WRONG to use the 'PackageDescription'
    -- store in the 'LocalBuildInfo' for the rest of @sdist@, because
    -- that would result in only the files that would be built
    -- according to the user's configure being packaged up.
    -- In fact, it is not obvious why we need to read the
    -- 'LocalBuildInfo' in the first place, except that we want
    -- to do some architecture-independent preprocessing which
    -- needs to be configured.  This is totally awful, see
    -- GH#130.

    (_, ppd) <- confPkgDescr hooks verbosity Nothing

362
363
364
    let pkg_descr0 = flattenPackageDescription ppd
    sanityCheckHookedBuildInfo pkg_descr0 pbi
    let pkg_descr = updatePackageDescription pbi pkg_descr0
365
        mlbi' = fmap (\lbi -> lbi { localPkgDescr = pkg_descr }) mlbi
366

367
368
    sDistHook hooks pkg_descr mlbi' hooks flags'
    postSDist hooks args flags' pkg_descr mlbi'
369
370
  where
    verbosity = fromFlag (sDistVerbosity flags)
371

372
testAction :: UserHooks -> TestFlags -> Args -> IO ()
ttuegel's avatar
ttuegel committed
373
testAction hooks flags args = do
374
375
376
377
    distPref <- findDistPrefOrDefault (testDistPref flags)
    let verbosity = fromFlag $ testVerbosity flags
        flags' = flags { testDistPref = toFlag distPref }

378
    localBuildInfo <- getBuildConfig hooks verbosity distPref
ttuegel's avatar
ttuegel committed
379
    let pkg_descr = localPkgDescr localBuildInfo
Ian Lynagh's avatar
Ian Lynagh committed
380
    -- It is safe to do 'runTests' before the new test handler because the
ttuegel's avatar
ttuegel committed
381
382
383
    -- default action is a no-op and if the package uses the old test interface
    -- the new handler will find no tests.
    runTests hooks args False pkg_descr localBuildInfo
384
    hookedActionWithArgs preTest testHook postTest
385
            (getBuildConfig hooks verbosity distPref)
386
            hooks flags' args
387

tibbe's avatar
tibbe committed
388
389
benchAction :: UserHooks -> BenchmarkFlags -> Args -> IO ()
benchAction hooks flags args = do
390
391
392
    distPref <- findDistPrefOrDefault (benchmarkDistPref flags)
    let verbosity = fromFlag $ benchmarkVerbosity flags
        flags' = flags { benchmarkDistPref = toFlag distPref }
tibbe's avatar
tibbe committed
393
394
    hookedActionWithArgs preBench benchHook postBench
            (getBuildConfig hooks verbosity distPref)
395
            hooks flags' args
tibbe's avatar
tibbe committed
396

397
registerAction :: UserHooks -> RegisterFlags -> Args -> IO ()
398
399
400
401
402
403
registerAction hooks flags args = do
    distPref <- findDistPrefOrDefault (regDistPref flags)
    let verbosity = fromFlag $ regVerbosity flags
        flags' = flags { regDistPref = toFlag distPref }
    hookedAction preReg regHook postReg
                 (getBuildConfig hooks verbosity distPref)
404
                 hooks flags' { regArgs = args } args
405
406

unregisterAction :: UserHooks -> RegisterFlags -> Args -> IO ()
407
408
409
410
411
412
413
unregisterAction hooks flags args = do
    distPref <- findDistPrefOrDefault (regDistPref flags)
    let verbosity = fromFlag $ regVerbosity flags
        flags' = flags { regDistPref = toFlag distPref }
    hookedAction preUnreg unregHook postUnreg
                 (getBuildConfig hooks verbosity distPref)
                 hooks flags' args
414
415
416
417
418
419
420
421

hookedAction :: (UserHooks -> Args -> flags -> IO HookedBuildInfo)
        -> (UserHooks -> PackageDescription -> LocalBuildInfo
                      -> UserHooks -> flags -> IO ())
        -> (UserHooks -> Args -> flags -> PackageDescription
                      -> LocalBuildInfo -> IO ())
        -> IO LocalBuildInfo
        -> UserHooks -> flags -> Args -> IO ()
tibbe's avatar
tibbe committed
422
hookedAction pre_hook cmd_hook =
423
424
    hookedActionWithArgs pre_hook (\h _ pd lbi uh flags ->
                                     cmd_hook h pd lbi uh flags)
tibbe's avatar
tibbe committed
425
426
427
428
429
430
431
432

hookedActionWithArgs :: (UserHooks -> Args -> flags -> IO HookedBuildInfo)
        -> (UserHooks -> Args -> PackageDescription -> LocalBuildInfo
                      -> UserHooks -> flags -> IO ())
        -> (UserHooks -> Args -> flags -> PackageDescription
                      -> LocalBuildInfo -> IO ())
        -> IO LocalBuildInfo
        -> UserHooks -> flags -> Args -> IO ()
433
434
hookedActionWithArgs pre_hook cmd_hook post_hook
  get_build_config hooks flags args = do
435
   pbi <- pre_hook hooks args flags
436
437
   lbi0 <- get_build_config
   let pkg_descr0 = localPkgDescr lbi0
438
   sanityCheckHookedBuildInfo pkg_descr0 pbi
439
   let pkg_descr = updatePackageDescription pbi pkg_descr0
440
441
442
       lbi = lbi0 { localPkgDescr = pkg_descr }
   cmd_hook hooks args pkg_descr lbi hooks flags
   post_hook hooks args flags pkg_descr lbi
443
444

sanityCheckHookedBuildInfo :: PackageDescription -> HookedBuildInfo -> IO ()
445
446
447
448
449
450
451
452
sanityCheckHookedBuildInfo PackageDescription { library = Nothing } (Just _,_)
    = die $ "The buildinfo contains info for a library, "
         ++ "but the package does not have a library."

sanityCheckHookedBuildInfo pkg_descr (_, hookExes)
    | not (null nonExistant)
    = die $ "The buildinfo contains info for an executable called '"
         ++ "executable with that name."
453
  where
454
455
456
    pkgExeNames  = nub (map exeName (executables pkg_descr))
    hookExeNames = nub (map fst hookExes)
    nonExistant  = hookExeNames \\ pkgExeNames
457
458
459

sanityCheckHookedBuildInfo _ _ = return ()

ijones's avatar
ijones committed
460

461
462
463
464
465
getBuildConfig :: UserHooks -> Verbosity -> FilePath -> IO LocalBuildInfo
getBuildConfig hooks verbosity distPref = do
  lbi_wo_programs <- getPersistBuildConfig distPref
  -- Restore info about unconfigured programs, since it is not serialized
  let lbi = lbi_wo_programs {
466
    withPrograms = restoreProgramDb
467
                     (builtinPrograms ++ hookedPrograms hooks)
468
                     (withPrograms lbi_wo_programs)
469
  }
470

471
472
473
474
475
  case pkgDescrFile lbi of
    Nothing -> return lbi
    Just pkg_descr_file -> do
      outdated <- checkPersistBuildConfigOutdated distPref pkg_descr_file
      if outdated
476
        then reconfigure pkg_descr_file lbi
477
478
        else return lbi

479
480
481
482
  where
    reconfigure :: FilePath -> LocalBuildInfo -> IO LocalBuildInfo
    reconfigure pkg_descr_file lbi = do
      notice verbosity $ pkg_descr_file ++ " has been changed. "
refold's avatar
refold committed
483
                      ++ "Re-configuring with most recently used options. "
484
485
486
487
488
                      ++ "If this fails, please run configure manually.\n"
      let cFlags = configFlags lbi
      let cFlags' = cFlags {
            -- Since the list of unconfigured programs is not serialized,
            -- restore it to the same value as normally used at the beginning
Ian D. Bollinger's avatar
Ian D. Bollinger committed
489
            -- of a configure run:
490
            configPrograms_ = restoreProgramDb
491
                               (builtinPrograms ++ hookedPrograms hooks)
492
                               `fmap` configPrograms_ cFlags,
493
494
495
496

            -- Use the current, not saved verbosity level:
            configVerbosity = Flag verbosity
          }
497
      configureAction hooks cFlags' (extraConfigArgs lbi)
498
499


Simon Marlow's avatar
Simon Marlow committed
500
501
502
-- --------------------------------------------------------------------------
-- Cleaning

503
504
clean :: PackageDescription -> CleanFlags -> IO ()
clean pkg_descr flags = do
505
    let distPref = fromFlagOrDefault defaultDistPref $ cleanDistPref flags
506
    notice verbosity "cleaning..."
507

508
    maybeConfig <- if fromFlag (cleanSaveConf flags)
509
                     then maybeGetPersistBuildConfig distPref
510
                     else return Nothing
511
512
513

    -- remove the whole dist/ directory rather than tracking exactly what files
    -- we created in there.
514
515
516
    chattyTry "removing dist/" $ do
      exists <- doesDirectoryExist distPref
      when exists (removeDirectoryRecursive distPref)
517
518

    -- Any extra files the user wants to remove
519
    traverse_ removeFileOrDirectory (extraTmpFiles pkg_descr)
520

521
    -- If the user wanted to save the config, write it back
522
    traverse_ (writePersistBuildConfig distPref) maybeConfig
523

ijones's avatar
ijones committed
524
  where
525
        removeFileOrDirectory :: FilePath -> NoCallStackIO ()
ijones's avatar
ijones committed
526
527
528
529
        removeFileOrDirectory fname = do
            isDir <- doesDirectoryExist fname
            isFile <- doesFileExist fname
            if isDir then removeDirectoryRecursive fname
EyalLotem's avatar
EyalLotem committed
530
              else when isFile $ removeFile fname
531
        verbosity = fromFlag (cleanVerbosity flags)
ijones's avatar
ijones committed
532

Simon Marlow's avatar
Simon Marlow committed
533
534
535
-- --------------------------------------------------------------------------
-- Default hooks

536
-- | Hooks that correspond to a plain instantiation of the
Ian Lynagh's avatar
Ian Lynagh committed
537
-- \"simple\" build system
Simon Marlow's avatar
Simon Marlow committed
538
simpleUserHooks :: UserHooks
539
simpleUserHooks =
Simon Marlow's avatar
Simon Marlow committed
540
    emptyUserHooks {
541
       confHook  = configure,
542
       postConf  = finalChecks,
543
       buildHook = defaultBuildHook,
544
       replHook  = defaultReplHook,
545
546
       copyHook  = \desc lbi _ f -> install desc lbi f,
                   -- 'install' has correct 'copy' behavior with params
547
       testHook  = defaultTestHook,
tibbe's avatar
tibbe committed
548
       benchHook = defaultBenchHook,
549
       instHook  = defaultInstallHook,
550
       sDistHook = \p l h f -> sdist p l f srcPref (allSuffixHandlers h),
551
       cleanHook = \p _ _ f -> clean p f,
552
553
       hscolourHook = \p l h f -> hscolour p l (allSuffixHandlers h) f,
       haddockHook  = \p l h f -> haddock  p l (allSuffixHandlers h) f,
554
555
556
       regHook   = defaultRegHook,
       unregHook = \p l _ f -> unregister p l f
      }
557
558
  where
    finalChecks _args flags pkg_descr lbi =
559
      checkForeignDeps pkg_descr lbi (lessVerbose verbosity)
560
561
      where
        verbosity = fromFlag (configVerbosity flags)
562

Simon Marlow's avatar
Simon Marlow committed
563
-- | Basic autoconf 'UserHooks':
ijones's avatar
ijones committed
564
--
565
-- * 'postConf' runs @.\/configure@, if present.
ijones's avatar
ijones committed
566
--
567
568
-- * the pre-hooks 'preBuild', 'preClean', 'preCopy', 'preInst',
--   'preReg' and 'preUnreg' read additional build information from
569
--   /package/@.buildinfo@, if present.
ijones's avatar
ijones committed
570
571
--
-- Thus @configure@ can use local system information to generate
572
-- /package/@.buildinfo@ and possibly other files.
573

574
{-# DEPRECATED defaultUserHooks
Duncan Coutts's avatar
Duncan Coutts committed
575
     "Use simpleUserHooks or autoconfUserHooks, unless you need Cabal-1.2\n             compatibility in which case you must stick with defaultUserHooks" #-}
ijones's avatar
ijones committed
576
defaultUserHooks :: UserHooks
577
578
defaultUserHooks = autoconfUserHooks {
          confHook = \pkg flags -> do
579
                       let verbosity = fromFlag (configVerbosity flags)
EyalLotem's avatar
EyalLotem committed
580
                       warn verbosity
581
582
                         "defaultUserHooks in Setup script is deprecated."
                       confHook autoconfUserHooks pkg flags,
583
584
585
          postConf = oldCompatPostConf
    }
    -- This is the annoying old version that only runs configure if it exists.
Duncan Coutts's avatar
Duncan Coutts committed
586
    -- It's here for compatibility with existing Setup.hs scripts. See:
Ben Millwood's avatar
Ben Millwood committed
587
    -- https://github.com/haskell/cabal/issues/158
588
    where oldCompatPostConf args flags pkg_descr lbi
589
              = do let verbosity = fromFlag (configVerbosity flags)
590
591
                   confExists <- doesFileExist "configure"
                   when confExists $
592
                       runConfigureScript verbosity
593
                         backwardsCompatHack flags lbi
594
595

                   pbi <- getHookedBuildInfo verbosity
596
                   sanityCheckHookedBuildInfo pkg_descr pbi
597
                   let pkg_descr' = updatePackageDescription pbi pkg_descr
598
599
                       lbi' = lbi { localPkgDescr = pkg_descr' }
                   postConf simpleUserHooks args flags pkg_descr' lbi'
600

601
          backwardsCompatHack = True
Simon Marlow's avatar
Simon Marlow committed
602
603
604
605

autoconfUserHooks :: UserHooks
autoconfUserHooks
    = simpleUserHooks
ijones's avatar
ijones committed
606
      {
607
       postConf    = defaultPostConf,
608
609
       preBuild    = readHookWithArgs buildVerbosity,
       preCopy     = readHookWithArgs copyVerbosity,
610
611
612
613
614
615
       preClean    = readHook cleanVerbosity,
       preInst     = readHook installVerbosity,
       preHscolour = readHook hscolourVerbosity,
       preHaddock  = readHook haddockVerbosity,
       preReg      = readHook regVerbosity,
       preUnreg    = readHook regVerbosity
ijones's avatar
ijones committed
616
      }
617
618
    where defaultPostConf :: Args -> ConfigFlags -> PackageDescription
                          -> LocalBuildInfo -> IO ()
619
          defaultPostConf args flags pkg_descr lbi
620
              = do let verbosity = fromFlag (configVerbosity flags)
ijones's avatar
ijones committed
621
                   confExists <- doesFileExist "configure"
622
                   if confExists
623
                     then runConfigureScript verbosity
624
                            backwardsCompatHack flags lbi
625
                     else die "configure script not found."
626
627

                   pbi <- getHookedBuildInfo verbosity
628
                   sanityCheckHookedBuildInfo pkg_descr pbi
629
                   let pkg_descr' = updatePackageDescription pbi pkg_descr
630
631
                       lbi' = lbi { localPkgDescr = pkg_descr' }
                   postConf simpleUserHooks args flags pkg_descr' lbi'
632

633
          backwardsCompatHack = False
634

635
636
          readHookWithArgs :: (a -> Flag Verbosity) -> Args -> a
                           -> IO HookedBuildInfo
637
638
639
640
641
          readHookWithArgs get_verbosity _ flags = do
              getHookedBuildInfo verbosity
            where
              verbosity = fromFlag (get_verbosity flags)

642
          readHook :: (a -> Flag Verbosity) -> Args -> a -> IO HookedBuildInfo
643
          readHook get_verbosity a flags = do
644
              noExtraFlags a
645
646
647
648
              getHookedBuildInfo verbosity
            where
              verbosity = fromFlag (get_verbosity flags)

649
650
651
652
runConfigureScript :: Verbosity -> Bool -> ConfigFlags -> LocalBuildInfo
                   -> IO ()
runConfigureScript verbosity backwardsCompatHack flags lbi = do
  env <- getEnvironment
653
654
  let programDb = withPrograms lbi
  (ccProg, ccFlags) <- configureCCompiler verbosity programDb
655
  ccProgShort <- getShortPathName ccProg
656
657
658
659
660
661
  -- The C compiler's compilation and linker flags (e.g.
  -- "C compiler flags" and "Gcc Linker flags" from GHC) have already
  -- been merged into ccFlags, so we set both CFLAGS and LDFLAGS
  -- to ccFlags
  -- We don't try and tell configure which ld to use, as we don't have
  -- a way to pass its flags too
662
  let extraPath = fromNubList $ configProgramPathExtra flags
663
664
  let cflagsEnv = maybe (unwords ccFlags) (++ (" " ++ unwords ccFlags))
                  $ lookup "CFLAGS" env
665
      spSep = [searchPathSeparator]
666
667
668
669
      pathEnv = maybe (intercalate spSep extraPath)
                ((intercalate spSep extraPath ++ spSep)++) $ lookup "PATH" env
      overEnv = ("CFLAGS", Just cflagsEnv) :
                [("PATH", Just pathEnv) | not (null extraPath)]
670
      args' = args ++ ["CC=" ++ ccProgShort]
671
      shProg = simpleProgram "sh"
672
673
674
675
      progDb = modifyProgramSearchPath
               (\p -> map ProgramSearchPathDir extraPath ++ p) emptyProgramDb
  shConfiguredProg <- lookupProgram shProg
                      `fmap` configureProgram  verbosity shProg progDb
676
  case shConfiguredProg of
677
678
      Just sh -> runProgramInvocation verbosity
                 (programInvocation (sh {programOverrideEnv = overEnv}) args')
679
      Nothing -> die notFoundMsg
680
681

  where
682
    args = "./configure" : configureArgs backwardsCompatHack flags
683

684
685
    notFoundMsg = "The package has a './configure' script. "
               ++ "If you are on Windows, This requires a "
686
               ++ "Unix compatibility toolchain such as MinGW+MSYS or Cygwin. "
687
688
               ++ "If you are not on Windows, ensure that an 'sh' command "
               ++ "is discoverable in your path."
689

690
691
692
693
694
695
696
697
getHookedBuildInfo :: Verbosity -> IO HookedBuildInfo
getHookedBuildInfo verbosity = do
  maybe_infoFile <- defaultHookedPackageDesc
  case maybe_infoFile of
    Nothing       -> return emptyHookedBuildInfo
    Just infoFile -> do
      info verbosity $ "Reading parameters from " ++ infoFile
      readHookedBuildInfo verbosity infoFile
ijones's avatar
ijones committed
698

699
defaultTestHook :: Args -> PackageDescription -> LocalBuildInfo
700
                -> UserHooks -> TestFlags -> IO ()
701
702
defaultTestHook args pkg_descr localbuildinfo _ flags =
    test args pkg_descr localbuildinfo flags
703

tibbe's avatar
tibbe committed
704
705
706
707
708
defaultBenchHook :: Args -> PackageDescription -> LocalBuildInfo
                 -> UserHooks -> BenchmarkFlags -> IO ()
defaultBenchHook args pkg_descr localbuildinfo _ flags =
    bench args pkg_descr localbuildinfo flags

709
defaultInstallHook :: PackageDescription -> LocalBuildInfo
710
                   -> UserHooks -> InstallFlags -> IO ()
711
defaultInstallHook pkg_descr localbuildinfo _ flags = do
712
  let copyFlags = defaultCopyFlags {
713
714
715
                      copyDistPref   = installDistPref flags,
                      copyDest       = toFlag NoCopyDest,
                      copyVerbosity  = installVerbosity flags
716
717
718
                  }
  install pkg_descr localbuildinfo copyFlags
  let registerFlags = defaultRegisterFlags {
719
720
721
                          regDistPref  = installDistPref flags,
                          regInPlace   = installInPlace flags,
                          regPackageDB = installPackageDB flags,
722
723
724
                          regVerbosity = installVerbosity flags
                      }
  when (hasLibs pkg_descr) $ register pkg_descr localbuildinfo registerFlags
ijones's avatar
ijones committed
725

726
defaultBuildHook :: PackageDescription -> LocalBuildInfo
727
        -> UserHooks -> BuildFlags -> IO ()
728
defaultBuildHook pkg_descr localbuildinfo hooks flags =
729
  build pkg_descr localbuildinfo flags (allSuffixHandlers hooks)
ijones's avatar
ijones committed
730

731
732
733
734
735
defaultReplHook :: PackageDescription -> LocalBuildInfo
        -> UserHooks -> ReplFlags -> [String] -> IO ()
defaultReplHook pkg_descr localbuildinfo hooks flags args =
  repl pkg_descr localbuildinfo flags (allSuffixHandlers hooks) args

736
defaultRegHook :: PackageDescription -> LocalBuildInfo
737
        -> UserHooks -> RegisterFlags -> IO ()
738
defaultRegHook pkg_descr localbuildinfo _ flags =
ijones's avatar
ijones committed
739
740
    if hasLibs pkg_descr
    then register pkg_descr localbuildinfo flags
741
    else setupMessage (fromFlag (regVerbosity flags))
742
           "Package contains no library to register:" (packageId pkg_descr)