Setup.hs 46.3 KB
Newer Older
ijones's avatar
ijones committed
1
2
-----------------------------------------------------------------------------
-- |
3
-- Module      :  Distribution.Simple.Setup
ijones's avatar
ijones committed
4
5
6
7
-- Copyright   :  Isaac Jones 2003-2004
-- 
-- Maintainer  :  Isaac Jones <ijones@syntaxpolice.org>
-- Stability   :  alpha
ijones's avatar
ijones committed
8
-- Portability :  portable
ijones's avatar
ijones committed
9
--
ijones's avatar
ijones committed
10
11
-- Explanation: Data types and parser for the standard command-line
-- setup.  Will also return commands it doesn't know about.
ijones's avatar
ijones committed
12

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

43
44
module Distribution.Simple.Setup (

45
46
47
48
49
50
51
52
53
54
55
56
57
  GlobalFlags(..),   emptyGlobalFlags,   defaultGlobalFlags,   globalCommand,
  ConfigFlags(..),   emptyConfigFlags,   defaultConfigFlags,   configureCommand,
  CopyFlags(..),     emptyCopyFlags,     defaultCopyFlags,     copyCommand,
  InstallFlags(..),  emptyInstallFlags,  defaultInstallFlags,  installCommand,
  HaddockFlags(..),  emptyHaddockFlags,  defaultHaddockFlags,  haddockCommand,
  HscolourFlags(..), emptyHscolourFlags, defaultHscolourFlags, hscolourCommand,
  BuildFlags(..),    emptyBuildFlags,    defaultBuildFlags,    buildCommand,
  CleanFlags(..),    emptyCleanFlags,    defaultCleanFlags,    cleanCommand,
  MakefileFlags(..), emptyMakefileFlags, defaultMakefileFlags, makefileCommand,
  RegisterFlags(..), emptyRegisterFlags, defaultRegisterFlags, registerCommand,
                                                               unregisterCommand,
  SDistFlags(..),    emptySDistFlags,    defaultSDistFlags,    sdistCommand,
                                                               testCommand,
58
59
  CopyDest(..),
  configureArgs,
60

Duncan Coutts's avatar
Duncan Coutts committed
61
  Flag(..),
62
63
64
65
  toFlag,
  fromFlag,
  fromFlagOrDefault,
  flagToMaybe,
66
  flagToList,
ijones's avatar
ijones committed
67
                           ) where
ijones's avatar
ijones committed
68

69
import Distribution.Simple.Command
70
71
import Distribution.Simple.Compiler
         ( CompilerFlavor(..), defaultCompilerFlavor, PackageDB(..) )
72
import Distribution.Simple.Utils (wrapText)
73
import Distribution.Simple.Program (Program(..), ProgramConfiguration,
74
75
76
77
                             knownPrograms)
import Distribution.Simple.InstallDirs
         ( InstallDirs(..), CopyDest(..),
           PathTemplate, toPathTemplate, fromPathTemplate )
78
import Data.List (sort)
79
import Data.Char( toLower, isSpace )
80
import Data.Monoid (Monoid(..))
81
import Distribution.Verbosity
ijones's avatar
ijones committed
82

83
-- ------------------------------------------------------------
84
-- * Flag type
85
86
-- ------------------------------------------------------------

87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
-- | All flags are monoids, they come in two flavours:
--
-- 1. list flags eg
--
-- > --ghc-option=foo --ghc-option=bar
--
-- gives us all the values ["foo", "bar"]
--
-- 2. singular value flags, eg:
--
-- > --enable-foo --disable-foo
--
-- gives us Just False
-- So this Flag type is for the latter singular kind of flag.
-- Its monoid instance gives us the behaviour where it starts out as
-- 'NoFlag' and later flags override earlier ones.
--
data Flag a = Flag a | NoFlag deriving Show
105

106
107
108
instance Functor Flag where
  fmap f (Flag x) = Flag (f x)
  fmap _ NoFlag  = NoFlag
109

110
111
112
113
instance Monoid (Flag a) where
  mempty = NoFlag
  _ `mappend` f@(Flag _) = f
  f `mappend` NoFlag    = f
114

115
116
toFlag :: a -> Flag a
toFlag = Flag
Roberto Zunino's avatar
Roberto Zunino committed
117

118
119
120
fromFlag :: Flag a -> a
fromFlag (Flag x) = x
fromFlag NoFlag   = error "fromFlag NoFlag. Use fromFlagOrDefault"
121

122
123
124
fromFlagOrDefault :: a -> Flag a -> a
fromFlagOrDefault _   (Flag x) = x
fromFlagOrDefault def NoFlag   = def
125

126
127
128
flagToMaybe :: Flag a -> Maybe a
flagToMaybe (Flag x) = Just x
flagToMaybe NoFlag   = Nothing
Simon Marlow's avatar
Simon Marlow committed
129

130
131
132
flagToList :: Flag a -> [a]
flagToList (Flag x) = [x]
flagToList NoFlag   = []
133

134
135
136
-- ------------------------------------------------------------
-- * Global flags
-- ------------------------------------------------------------
Simon Marlow's avatar
Simon Marlow committed
137

138
139
140
141
142
-- In fact since individual flags types are monoids and these are just sets of
-- flags then they are also monoids pointwise. This turns out to be really
-- useful. The mempty is the set of empty flags and mappend allows us to
-- override specific flags. For example we can start with default flags and
-- override with the ones we get from a file or the command line, or both.
143

144
145
146
147
148
-- | Flags that apply at the top level, not to any sub-command.
data GlobalFlags = GlobalFlags {
    globalVersion        :: Flag Bool,
    globalNumericVersion :: Flag Bool
  }
149

150
151
152
153
154
defaultGlobalFlags :: GlobalFlags
defaultGlobalFlags  = GlobalFlags {
    globalVersion        = Flag False,
    globalNumericVersion = Flag False
  }
155
156

globalCommand :: CommandUI GlobalFlags
157
globalCommand = makeCommand name shortDesc longDesc defaultGlobalFlags options
158
159
160
161
162
163
164
165
166
167
168
169
170
171
  where
    name       = ""
    shortDesc  = ""
    longDesc   = Just $ \pname ->
         "Typical steps for installing Cabal packages:\n"
      ++ unlines [ "  " ++ pname ++ " " ++ x
                 | x <- ["configure", "build", "install"]]
      ++ "\nFor more information about a command, try '"
          ++ pname ++ " COMMAND --help'."
      ++ "\nThis Setup program uses the Haskell Cabal Infrastructure."
      ++ "\nSee http://www.haskell.org/cabal/ for more information.\n"
    options _  =
      [option ['V'] ["version"]
         "Print version information"
172
173
         globalVersion (\v flags -> flags { globalVersion = v })
         trueArg
174
175
      ,option [] ["numeric-version"]
         "Print just the version number"
176
177
         globalNumericVersion (\v flags -> flags { globalNumericVersion = v })
         trueArg
178
179
      ]

180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
emptyGlobalFlags :: GlobalFlags
emptyGlobalFlags = mempty

instance Monoid GlobalFlags where
  mempty = GlobalFlags {
    globalVersion        = mempty,
    globalNumericVersion = mempty
  }
  mappend a b = GlobalFlags {
    globalVersion        = combine globalVersion,
    globalNumericVersion = combine globalNumericVersion
  }
    where combine field = field a `mappend` field b

-- ------------------------------------------------------------
-- * Config flags
-- ------------------------------------------------------------

-- | Flags to @configure@ command
data ConfigFlags = ConfigFlags {
    --FIXME: the configPrograms is only here to pass info through to configure
    -- because the type of configure is constrained by the UserHooks.
    -- when we change UserHooks next we should pass the initial
    -- ProgramConfiguration directly and not via ConfigFlags
    configPrograms      :: ProgramConfiguration, -- ^All programs that cabal may run

    configProgramPaths  :: [(String, FilePath)], -- ^user specifed programs paths
    configProgramArgs   :: [(String, [String])], -- ^user specifed programs args
    configHcFlavor      :: Flag CompilerFlavor, -- ^The \"flavor\" of the compiler, sugh as GHC or Hugs.
    configHcPath        :: Flag FilePath, -- ^given compiler location
    configHcPkg         :: Flag FilePath, -- ^given hc-pkg location
    configVanillaLib    :: Flag Bool,     -- ^Enable vanilla library
    configProfLib       :: Flag Bool,     -- ^Enable profiling in the library
    configSharedLib     :: Flag Bool,     -- ^Build shared library
    configProfExe       :: Flag Bool,     -- ^Enable profiling in the executables.
    configConfigureArgs :: [String],      -- ^Extra arguments to @configure@
    configOptimization  :: Flag Bool,     -- ^Enable optimization.
217
218
    configProgPrefix    :: Flag PathTemplate, -- ^Installed executable prefix.
    configProgSuffix    :: Flag PathTemplate, -- ^Installed executable suffix.
219
220
221
222
    configInstallDirs   :: InstallDirs (Flag PathTemplate), -- ^Installation paths
    configScratchDir    :: Flag FilePath,

    configVerbose   :: Flag Verbosity, -- ^verbosity level
Duncan Coutts's avatar
Duncan Coutts committed
223
    configUserInstall :: Flag Bool,    -- ^The --user\/--global flag
224
    configPackageDB :: Flag PackageDB, -- ^Which package DB to use
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
    configGHCiLib   :: Flag Bool,      -- ^Enable compiling library for GHCi
    configSplitObjs :: Flag Bool,      -- ^Enable -split-objs with GHC
    configConfigurationsFlags :: [(String, Bool)]
  }
  deriving Show

defaultConfigFlags :: ProgramConfiguration -> ConfigFlags
defaultConfigFlags progConf = emptyConfigFlags {
    configPrograms     = progConf,
    configHcFlavor     = maybe NoFlag Flag defaultCompilerFlavor,
    configVanillaLib   = Flag True,
    configProfLib      = Flag False,
    configSharedLib    = Flag False,
    configProfExe      = Flag False,
    configOptimization = Flag True,
240
241
    configProgPrefix   = Flag (toPathTemplate ""),
    configProgSuffix   = Flag (toPathTemplate ""),
242
    configVerbose      = Flag normal,
243
    configUserInstall  = Flag False,           --TODO: reverse this
244
245
246
247
    configGHCiLib      = Flag True,
    configSplitObjs    = Flag False -- takes longer, so turn off by default
  }

248
configureCommand :: ProgramConfiguration -> CommandUI ConfigFlags
249
configureCommand progConf = makeCommand name shortDesc longDesc defaultFlags options
250
251
252
253
  where
    name       = "configure"
    shortDesc  = "Prepare to build the package."
    longDesc   = Just (\_ -> programFlagsDescription progConf)
254
    defaultFlags = defaultConfigFlags progConf
255
    options showOrParseArgs =
256
      [optionVerbose configVerbose (\v flags -> flags { configVerbose = v })
257
258
259

      ,option "g" ["ghc"]
         "compile with GHC"
260
261
         configHcFlavor (\v flags -> flags { configHcFlavor = v })
         (noArg (Flag GHC) (\f -> case f of Flag GHC -> True; _ -> False))
262
263
264

      ,option "" ["nhc98"]
         "compile with NHC"
265
266
         configHcFlavor (\v flags -> flags { configHcFlavor = v })
         (noArg (Flag NHC) (\f -> case f of Flag NHC -> True; _ -> False))
267
268
269

      ,option "" ["jhc"]
         "compile with JHC"
270
271
         configHcFlavor (\v flags -> flags { configHcFlavor = v })
         (noArg (Flag JHC) (\f -> case f of Flag JHC -> True; _ -> False))
272
273
274

      ,option "" ["hugs"]
         "compile with hugs"
275
276
         configHcFlavor (\v flags -> flags { configHcFlavor = v })
         (noArg (Flag Hugs) (\f -> case f of Flag Hugs -> True; _ -> False))
277
278
279

      ,option "w" ["with-compiler"]
         "give the path to a particular compiler"
280
281
         configHcPath (\v flags -> flags { configHcPath = v })
         (reqArgFlag "PATH")
282
283
284

      ,option "" ["with-hc-pkg"]
         "give the path to the package tool"
285
286
         configHcPkg (\v flags -> flags { configHcPkg = v })
         (reqArgFlag "PATH")
287
288
289

      ,option "" ["prefix"]
         "bake this prefix in preparation of installation"
290
291
         prefix (\v flags -> flags { prefix = v })
         installDirArg
292
293
294

      ,option "" ["bindir"]
         "installation directory for executables"
295
296
         bindir (\v flags -> flags { bindir = v })
         installDirArg
297
298
299

      ,option "" ["libdir"]
         "installation directory for libraries"
300
301
         libdir (\v flags -> flags { libdir = v })
         installDirArg
302
303
304

      ,option "" ["libsubdir"]
	 "subdirectory of libdir in which libs are installed"
305
306
         libsubdir (\v flags -> flags { libsubdir = v })
         installDirArg
307
308
309

      ,option "" ["libexecdir"]
	 "installation directory for program executables"
310
311
         libexecdir (\v flags -> flags { libexecdir = v })
         installDirArg
312
313
314

      ,option "" ["datadir"]
	 "installation directory for read-only data"
315
316
         datadir (\v flags -> flags { datadir = v })
         installDirArg
317
318
319

      ,option "" ["datasubdir"]
	 "subdirectory of datadir in which data files are installed"
320
321
         datasubdir (\v flags -> flags { datasubdir = v })
         installDirArg
322
323
324

      ,option "" ["docdir"]
	 "installation directory for documentation"
325
326
         docdir (\v flags -> flags { docdir = v })
         installDirArg
327
328
329

      ,option "" ["htmldir"]
	 "installation directory for HTML documentation"
330
331
         htmldir (\v flags -> flags { htmldir = v })
         installDirArg
332

333
      ,option "" ["haddockdir"]
334
	 "installation directory for haddock interfaces"
335
336
         haddockdir (\v flags -> flags { haddockdir = v })
         installDirArg
337
338
339

      ,option "b" ["scratchdir"]
         "directory to receive the built package [dist/scratch]"
340
341
         configScratchDir (\v flags -> flags { configScratchDir = v })
         (reqArgFlag "DIR")
342

343
344
      ,option "" ["program-prefix"]
          "prefix to be applied to installed executables"
345
346
347
          configProgPrefix 
          (\v flags -> flags { configProgPrefix = v })
          (reqPathTemplateArgFlag "PREFIX")
348
349
350

      ,option "" ["program-suffix"]
          "suffix to be applied to installed executables"
351
352
          configProgSuffix (\v flags -> flags { configProgSuffix = v } )
          (reqPathTemplateArgFlag "SUFFIX")
353

354
355
      ,option "" ["enable-library-vanilla"]
         "Enable vanilla libraries"
356
357
         configVanillaLib (\v flags -> flags { configVanillaLib = v })
         trueArg
358
359
360

      ,option "" ["disable-library-vanilla"]
         "Disable vanilla libraries"
361
362
          configVanillaLib (\v flags -> flags { configVanillaLib = v })
          falseArg
363
364
365

      ,option "p" ["enable-library-profiling"]
         "Enable library profiling"
366
367
         configProfLib (\v flags -> flags { configProfLib = v })
         trueArg
368
369
370

      ,option "" ["disable-library-profiling"]
         "Disable library profiling"
371
372
         configProfLib (\v flags -> flags { configProfLib = v })
         falseArg
373
374
375

      ,option "" ["enable-shared"]
         "Enable shared library"
376
377
         configSharedLib (\v flags -> flags { configSharedLib = v })
         trueArg
378
379
380

      ,option "" ["disable-shared"]
         "Disable shared library"
381
382
         configSharedLib (\v flags -> flags { configSharedLib = v })
         falseArg
383
384
385

      ,option "" ["enable-executable-profiling"]
         "Enable executable profiling"
386
387
         configProfExe (\v flags -> flags { configProfExe = v })
         trueArg
388
389
390

      ,option "" ["disable-executable-profiling"]
         "Disable executable profiling"
391
392
         configProfExe (\v flags -> flags { configProfExe = v })
         falseArg
393

394
395
396
      ,option "O" ("enable-optimization": case showOrParseArgs of
                      -- Allow British English spelling:
                      ShowArgs -> []; ParseArgs -> ["enable-optimisation"])
397
         "Build with optimization"
398
399
         configOptimization (\v flags -> flags { configOptimization = v })
         trueArg
400

401
402
403
      ,option "" ("disable-optimization": case showOrParseArgs of
                      -- Allow British English spelling:
                      ShowArgs -> []; ParseArgs -> ["disable-optimisation"])
404
         "Build without optimization"
405
406
         configOptimization (\v flags -> flags { configOptimization = v })
         falseArg
407
408
409

      ,option "" ["enable-library-for-ghci"]
         "compile library for use with GHCi"
410
411
         configGHCiLib (\v flags -> flags { configGHCiLib = v })
         trueArg
412
413
414

      ,option "" ["disable-library-for-ghci"]
         "do not compile libraries for GHCi"
415
416
         configGHCiLib (\v flags -> flags { configGHCiLib = v })
         falseArg
417
418
419

      ,option "" ["enable-split-objs"]
         "split library into smaller objects to reduce binary sizes (GHC 6.6+)"
420
421
         configSplitObjs (\v flags -> flags { configSplitObjs = v })
         trueArg
422
423
424

      ,option "" ["disable-split-objs"]
         "split library into smaller objects to reduce binary sizes (GHC 6.6+)"
425
426
         configSplitObjs (\v flags -> flags { configSplitObjs = v })
         falseArg
427
428
429

      ,option "" ["configure-option"]
         "Extra option for configure"
430
431
         configConfigureArgs (\v flags -> flags { configConfigureArgs = v })
         (reqArg "OPT" (\x -> [x]) id)
432
433

      ,option "" ["user"]
434
435
436
         "do a per-user installation"
         configUserInstall (\v flags -> flags { configUserInstall = v })
         trueArg
437
438

      ,option "" ["global"]
439
440
441
         "(default) do a system-wide installation"
         configUserInstall (\v flags -> flags { configUserInstall = v })
         falseArg
442

443
444
445
446
447
448
449
450
      ,option "" ["package-db"]
         "Use a specific package database (to satisfy dependencies and register in)"
         configPackageDB (\v flags -> flags { configPackageDB = v })
         (reqArg "PATH" (Flag . SpecificPackageDB)
                        (\f -> case f of
                                 Flag (SpecificPackageDB db) -> [db]
                                 _ -> []))

451
452
      ,option "f" ["flags"]
         "Force values for the given flags in Cabal conditionals in the .cabal file.  E.g., --flags=\"debug -usebytestrings\" forces the flag \"debug\" to true and \"usebytestrings\" to false."
453
454
455
         configConfigurationsFlags (\v flags -> flags { configConfigurationsFlags = v })
         (reqArg "FLAGS" readFlagList showFlagList)

456
      ]
457
458
459
460
      ++ programConfigurationPaths   progConf showOrParseArgs
           configProgramPaths (\v fs -> fs { configProgramPaths = v })
      ++ programConfigurationOptions progConf showOrParseArgs
           configProgramArgs (\v fs -> fs { configProgramArgs = v })
461

462
463
    readFlagList :: String -> [(String, Bool)]
    readFlagList = map tagWithValue . words
464
465
      where tagWithValue ('-':fname) = (map toLower fname, False)
            tagWithValue fname       = (map toLower fname, True)
466
467
468
469
    
    showFlagList :: [(String, Bool)] -> [String]
    showFlagList fs = [ if not set then '-':fname else fname | (fname, set) <- fs]

470
    installDirArg get set = reqArgFlag "DIR"
471
472
473
      (fmap fromPathTemplate.get.configInstallDirs)
      (\v flags -> flags { configInstallDirs =
                             set (fmap toPathTemplate v) (configInstallDirs flags)})
474
475
476
477

    reqPathTemplateArgFlag title get set = reqArgFlag title
      (fmap fromPathTemplate.get)
      (\v flags -> set (fmap toPathTemplate v) flags)
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495

emptyConfigFlags :: ConfigFlags
emptyConfigFlags = mempty

instance Monoid ConfigFlags where
  mempty = ConfigFlags {
    configPrograms      = error "FIXME: remove configPrograms",
    configProgramPaths  = mempty,
    configProgramArgs   = mempty,
    configHcFlavor      = mempty,
    configHcPath        = mempty,
    configHcPkg         = mempty,
    configVanillaLib    = mempty,
    configProfLib       = mempty,
    configSharedLib     = mempty,
    configProfExe       = mempty,
    configConfigureArgs = mempty,
    configOptimization  = mempty,
496
497
    configProgPrefix    = mempty,
    configProgSuffix    = mempty,
498
499
500
    configInstallDirs   = mempty,
    configScratchDir    = mempty,
    configVerbose       = mempty,
501
    configUserInstall   = mempty,
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
    configPackageDB     = mempty,
    configGHCiLib       = mempty,
    configSplitObjs     = mempty,
    configConfigurationsFlags = mempty
  }
  mappend a b =  ConfigFlags {
    configPrograms      = configPrograms b,
    configProgramPaths  = combine configProgramPaths,
    configProgramArgs   = combine configProgramArgs,
    configHcFlavor      = combine configHcFlavor,
    configHcPath        = combine configHcPath,
    configHcPkg         = combine configHcPkg,
    configVanillaLib    = combine configVanillaLib,
    configProfLib       = combine configProfLib,
    configSharedLib     = combine configSharedLib,
    configProfExe       = combine configProfExe,
    configConfigureArgs = combine configConfigureArgs,
    configOptimization  = combine configOptimization,
520
521
    configProgPrefix    = combine configProgPrefix,
    configProgSuffix    = combine configProgSuffix,
522
523
524
    configInstallDirs   = combine configInstallDirs,
    configScratchDir    = combine configScratchDir,
    configVerbose       = combine configVerbose,
525
    configUserInstall   = combine configUserInstall,
526
527
528
529
530
531
    configPackageDB     = combine configPackageDB,
    configGHCiLib       = combine configGHCiLib,
    configSplitObjs     = combine configSplitObjs,
    configConfigurationsFlags = combine configConfigurationsFlags
  }
    where combine field = field a `mappend` field b
532

533
534
535
-- ------------------------------------------------------------
-- * Copy flags
-- ------------------------------------------------------------
536

537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
-- | Flags to @copy@: (destdir, copy-prefix (backwards compat), verbosity)
data CopyFlags = CopyFlags {
    copyDest    :: Flag CopyDest,
    copyVerbose :: Flag Verbosity
  }
  deriving Show

defaultCopyFlags :: CopyFlags
defaultCopyFlags  = CopyFlags {
    copyDest    = Flag NoCopyDest,
    copyVerbose = Flag normal
  }

copyCommand :: CommandUI CopyFlags
copyCommand = makeCommand name shortDesc longDesc defaultCopyFlags options
  where
    name       = "copy"
    shortDesc  = "Copy the files into the install locations."
    longDesc   = Just $ \_ ->
          "Does not call register, and allows a prefix at install time\n"
       ++ "Without the --destdir flag, configure determines location.\n"
    options _  =
      [optionVerbose copyVerbose (\v flags -> flags { copyVerbose = v })
560

561
562
563
564
565
      ,option "" ["destdir"]
         "directory to copy files to, prepended to installation directories"
         copyDest (\v flags -> flags { copyDest = v })
         (reqArg "DIR" (Flag . CopyTo)
                       (\f -> case f of Flag (CopyTo p) -> [p]; _ -> []))
566

567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
      ,option "" ["copy-prefix"]
         "[DEPRECATED, directory to copy files to instead of prefix]"
         copyDest (\v flags -> flags { copyDest = v })
         (reqArg "DIR" (Flag . CopyPrefix)
                       (\f -> case f of Flag (CopyPrefix p) -> [p]; _ -> []))

      ]

emptyCopyFlags :: CopyFlags
emptyCopyFlags = mempty

instance Monoid CopyFlags where
  mempty = CopyFlags {
    copyDest    = mempty,
    copyVerbose = mempty
  }
  mappend a b = CopyFlags {
    copyDest    = combine copyDest,
    copyVerbose = combine copyVerbose
  }
    where combine field = field a `mappend` field b

-- ------------------------------------------------------------
-- * Install flags
-- ------------------------------------------------------------

-- | Flags to @install@: (package db, verbosity)
data InstallFlags = InstallFlags {
    installPackageDB :: Flag PackageDB,
    installVerbose   :: Flag Verbosity
  }
  deriving Show

defaultInstallFlags :: InstallFlags
defaultInstallFlags  = InstallFlags {
    installPackageDB = NoFlag,
    installVerbose   = Flag normal
  }

installCommand :: CommandUI InstallFlags
installCommand = makeCommand name shortDesc longDesc defaultInstallFlags options
608
  where
609
610
611
612
613
614
615
616
    name       = "install"
    shortDesc  = "Copy the files into the install locations. Run register."
    longDesc   = Just $ \_ ->
         "Unlike the copy command, install calls the register command.\n"
      ++ "If you want to install into a location that is not what was\n"
      ++ "specified in the configure step, use the copy command.\n"
    options _  =
      [optionVerbose installVerbose (\v flags -> flags { installVerbose = v })
617

618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
      ,option "" ["user"]
         "upon registration, register this package in the user's local package database"
         installPackageDB (\v flags -> flags { installPackageDB = v })
         (noArg (Flag UserPackageDB)
                (\f -> case f of Flag UserPackageDB -> True; _ -> False))

      ,option "" ["global"]
         "(default; override with configure) upon registration, register this package in the system-wide package database"
         installPackageDB (\v flags -> flags { installPackageDB = v })
         (noArg (Flag GlobalPackageDB)
                (\f -> case f of Flag GlobalPackageDB -> True; _ -> False))

      ]

emptyInstallFlags :: InstallFlags
emptyInstallFlags = mempty

instance Monoid InstallFlags where
  mempty = InstallFlags{
    installPackageDB = mempty,
    installVerbose   = mempty
  }
  mappend a b = InstallFlags{
    installPackageDB = combine installPackageDB,
    installVerbose   = combine installVerbose
  }
    where combine field = field a `mappend` field b

-- ------------------------------------------------------------
-- * SDist flags
-- ------------------------------------------------------------

-- | Flags to @sdist@: (snapshot, verbosity)
data SDistFlags = SDistFlags {
    sDistSnapshot :: Flag Bool,
    sDistVerbose  :: Flag Verbosity
  }
  deriving Show

defaultSDistFlags :: SDistFlags
defaultSDistFlags = SDistFlags {
    sDistSnapshot = Flag False,
    sDistVerbose  = Flag normal
  }

sdistCommand :: CommandUI SDistFlags
sdistCommand = makeCommand name shortDesc longDesc defaultSDistFlags options
665
  where
666
667
668
669
670
    name       = "sdist"
    shortDesc  = "Generate a source distribution file (.tar.gz)."
    longDesc   = Nothing
    options _  =
      [optionVerbose sDistVerbose (\v flags -> flags { sDistVerbose = v })
671

672
673
674
675
676
      ,option "" ["snapshot"]
         "Produce a snapshot source distribution"
         sDistSnapshot (\v flags -> flags { sDistSnapshot = v })
         trueArg
      ]
677

678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
emptySDistFlags :: SDistFlags
emptySDistFlags = mempty

instance Monoid SDistFlags where
  mempty = SDistFlags {
    sDistSnapshot = mempty,
    sDistVerbose  = mempty
  }
  mappend a b = SDistFlags {
    sDistSnapshot = combine sDistSnapshot,
    sDistVerbose  = combine sDistVerbose
  }
    where combine field = field a `mappend` field b

-- ------------------------------------------------------------
-- * Register flags
-- ------------------------------------------------------------

-- | Flags to @register@ and @unregister@: (user package, gen-script,
-- in-place, verbosity)
data RegisterFlags = RegisterFlags {
    regPackageDB   :: Flag PackageDB,
    regGenScript   :: Flag Bool,
    regGenPkgConf  :: Flag (Maybe FilePath),
    regInPlace     :: Flag Bool,
    regVerbose     :: Flag Verbosity
  }
  deriving Show

defaultRegisterFlags :: RegisterFlags
defaultRegisterFlags = RegisterFlags {
    regPackageDB   = NoFlag,
    regGenScript   = Flag False,
    regGenPkgConf  = Flag Nothing,
    regInPlace     = Flag False,
    regVerbose     = Flag normal
  }

registerCommand :: CommandUI RegisterFlags
registerCommand = makeCommand name shortDesc longDesc defaultRegisterFlags options
718
  where
719
720
    name       = "register"
    shortDesc  = "Register this package with the compiler."
721
    longDesc   = Nothing
722
723
    options _  =
      [optionVerbose regVerbose (\v flags -> flags { regVerbose = v })
724

725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
      ,option "" ["user"]
         "upon registration, register this package in the user's local package database"
         regPackageDB (\v flags -> flags { regPackageDB = v })
         (noArg (Flag UserPackageDB)
                (\f -> case f of Flag UserPackageDB -> True; _ -> False))

      ,option "" ["global"]
         "(default) upon registration, register this package in the system-wide package database"
         regPackageDB (\v flags -> flags { regPackageDB = v })
         (noArg (Flag GlobalPackageDB)
                (\f -> case f of Flag GlobalPackageDB -> True; _ -> False))

      ,option "" ["inplace"]
         "register the package in the build location, so it can be used without being installed"
         regInPlace (\v flags -> flags { regInPlace = v })
         trueArg
741

742
743
744
745
746
747
748
749
750
751
752
753
754
      ,option "" ["gen-script"]
         "instead of registering, generate a script to register later"
         regGenScript (\v flags -> flags { regGenScript = v })
         trueArg

      ,option "" ["gen-pkg-config"]
         "instead of registering, generate a package registration file"
         regGenPkgConf (\v flags -> flags { regGenPkgConf  = v })
         (optArg "PKG" Flag flagToList)
      ]

unregisterCommand :: CommandUI RegisterFlags
unregisterCommand = makeCommand name shortDesc longDesc defaultRegisterFlags options
755
  where
756
757
    name       = "unregister"
    shortDesc  = "Unregister this package with the compiler."
758
759
    longDesc   = Nothing
    options _  =
760
      [optionVerbose regVerbose (\v flags -> flags { regVerbose = v })
761

762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
      ,option "" ["user"]
         "unregister this package in the user's local package database"
         regPackageDB (\v flags -> flags { regPackageDB = v })
         (noArg (Flag UserPackageDB)
                (\f -> case f of Flag UserPackageDB -> True; _ -> False))

      ,option "" ["global"]
         "(default) unregister this package in the system-wide package database"
         regPackageDB (\v flags -> flags { regPackageDB = v })
         (noArg (Flag GlobalPackageDB)
                (\f -> case f of Flag GlobalPackageDB -> True; _ -> False))

      ,option "" ["gen-script"]
         "Instead of performing the unregister command, generate a script to unregister later"
         regGenScript (\v flags -> flags { regGenScript = v })
         trueArg
778
779
      ]

780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
emptyRegisterFlags :: RegisterFlags
emptyRegisterFlags = mempty

instance Monoid RegisterFlags where
  mempty = RegisterFlags {
    regPackageDB   = mempty,
    regGenScript   = mempty,
    regGenPkgConf  = mempty,
    regInPlace     = mempty,
    regVerbose     = mempty
  }
  mappend a b = RegisterFlags {
    regPackageDB   = combine regPackageDB,
    regGenScript   = combine regGenScript,
    regGenPkgConf  = combine regGenPkgConf,
    regInPlace     = combine regInPlace,
    regVerbose     = combine regVerbose
  }
    where combine field = field a `mappend` field b

-- ------------------------------------------------------------
-- * HsColour flags
-- ------------------------------------------------------------

data HscolourFlags = HscolourFlags {
    hscolourCSS         :: Flag FilePath,
    hscolourExecutables :: Flag Bool,
    hscolourVerbose     :: Flag Verbosity
  }
  deriving Show

emptyHscolourFlags :: HscolourFlags
emptyHscolourFlags = mempty

defaultHscolourFlags :: HscolourFlags
defaultHscolourFlags = HscolourFlags {
    hscolourCSS         = NoFlag,
    hscolourExecutables = Flag False,
    hscolourVerbose     = Flag normal
  }

instance Monoid HscolourFlags where
  mempty = HscolourFlags {
    hscolourCSS         = mempty,
    hscolourExecutables = mempty,
    hscolourVerbose     = mempty
  }
  mappend a b = HscolourFlags {
    hscolourCSS         = combine hscolourCSS,
    hscolourExecutables = combine hscolourExecutables,
    hscolourVerbose     = combine hscolourVerbose
  }
    where combine field = field a `mappend` field b

hscolourCommand :: CommandUI HscolourFlags
hscolourCommand = makeCommand name shortDesc longDesc defaultHscolourFlags options
836
837
838
839
840
  where
    name       = "hscolour"
    shortDesc  = "Generate HsColour colourised code, in HTML format."
    longDesc   = Just (\_ -> "Requires hscolour.")
    options _  =
841
      [optionVerbose hscolourVerbose (\v flags -> flags { hscolourVerbose = v })
842
843
844

      ,option "" ["executables"]
         "Run hscolour for Executables targets"
845
846
         hscolourExecutables (\v flags -> flags { hscolourExecutables = v })
         trueArg
847
848
849

      ,option "" ["css"]
         "Use a cascading style sheet"
850
851
         hscolourCSS (\v flags -> flags { hscolourCSS = v })
         (reqArgFlag "PATH")
852
853
      ]

854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
-- ------------------------------------------------------------
-- * Haddock flags
-- ------------------------------------------------------------

data HaddockFlags = HaddockFlags {
    haddockHoogle       :: Flag Bool,
    haddockHtmlLocation :: Flag String,
    haddockExecutables  :: Flag Bool,
    haddockCss          :: Flag FilePath,
    haddockHscolour     :: Flag Bool,
    haddockHscolourCss  :: Flag FilePath,
    haddockVerbose      :: Flag Verbosity
  }
  deriving Show

defaultHaddockFlags :: HaddockFlags
defaultHaddockFlags  = HaddockFlags {
    haddockHoogle       = Flag False,
    haddockHtmlLocation = NoFlag,
    haddockExecutables  = Flag False,
    haddockCss          = NoFlag,
    haddockHscolour     = Flag False,
    haddockHscolourCss  = NoFlag,
    haddockVerbose      = Flag normal
  }

haddockCommand :: CommandUI HaddockFlags
haddockCommand = makeCommand name shortDesc longDesc defaultHaddockFlags options
882
883
884
885
886
  where
    name       = "haddock"
    shortDesc  = "Generate Haddock HTML documentation."
    longDesc   = Just (\_ -> "Requires cpphs and haddock.\n")
    options _  =
887
      [optionVerbose haddockVerbose (\v flags -> flags { haddockVerbose = v })
888
889
890

      ,option "" ["hoogle"]
         "Generate a hoogle database"
891
892
         haddockHoogle (\v flags -> flags { haddockHoogle = v })
         trueArg
893
894
895

      ,option "" ["html-location"]
         "Location of HTML documentation for pre-requisite packages"
896
897
         haddockHtmlLocation (\v flags -> flags { haddockHtmlLocation = v })
         (reqArgFlag "URL")
898
899
900

      ,option "" ["executables"]
         "Run haddock for Executables targets"
901
902
         haddockExecutables (\v flags -> flags { haddockExecutables = v })
         trueArg
903
904
905

      ,option "" ["css"]
         "Use PATH as the haddock stylesheet"
906
907
         haddockCss (\v flags -> flags { haddockCss = v })
         (reqArgFlag "PATH")
908
909
910

      ,option "" ["hyperlink-source"]
         "Hyperlink the documentation to the source code (using HsColour)"
911
912
         haddockHscolour (\v flags -> flags { haddockHscolour = v })
         trueArg
913
914
915

      ,option "" ["hscolour-css"]
         "Use PATH as the HsColour stylesheet"
916
917
         haddockHscolourCss (\v flags -> flags { haddockHscolourCss = v })
         (reqArgFlag "PATH")
918
919
      ]

920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
emptyHaddockFlags :: HaddockFlags
emptyHaddockFlags = mempty

instance Monoid HaddockFlags where
  mempty = HaddockFlags {
    haddockHoogle       = mempty,
    haddockHtmlLocation = mempty,
    haddockExecutables  = mempty,
    haddockCss          = mempty,
    haddockHscolour     = mempty,
    haddockHscolourCss  = mempty,
    haddockVerbose      = mempty
  }
  mappend a b = HaddockFlags {
    haddockHoogle       = combine haddockHoogle,
    haddockHtmlLocation = combine haddockHtmlLocation,
    haddockExecutables  = combine haddockExecutables,
    haddockCss          = combine haddockCss,
    haddockHscolour     = combine haddockHscolour,
    haddockHscolourCss  = combine haddockHscolourCss,
    haddockVerbose      = combine haddockVerbose
  }
    where combine field = field a `mappend` field b

-- ------------------------------------------------------------
-- * Clean flags
-- ------------------------------------------------------------
947

948
949
950
951
952
953
954
955
956
957
958
959
960
961
data CleanFlags = CleanFlags {
    cleanSaveConf  :: Flag Bool,
    cleanVerbose   :: Flag Verbosity
  }
  deriving Show

defaultCleanFlags :: CleanFlags
defaultCleanFlags  = CleanFlags {
    cleanSaveConf = Flag False,
    cleanVerbose  = Flag normal
  }

cleanCommand :: CommandUI CleanFlags
cleanCommand = makeCommand name shortDesc longDesc defaultCleanFlags options
962
963
964
965
966
  where
    name       = "clean"
    shortDesc  = "Clean up after a build."
    longDesc   = Just (\_ -> "Removes .hi, .o, preprocessed sources, etc.\n")
    options _  =
967
      [optionVerbose cleanVerbose (\v flags -> flags { cleanVerbose = v })
968
969
970

      ,option "s" ["save-configure"]
         "Do not remove the configuration file (dist/setup-config) during cleaning.  Saves need to reconfigure."
971
972
         cleanSaveConf (\v flags -> flags { cleanSaveConf = v })
         trueArg
973
974
      ]

975
976
977
978
979
980
981
982
983
984
985
986
987
emptyCleanFlags :: CleanFlags
emptyCleanFlags = mempty

instance Monoid CleanFlags where
  mempty = CleanFlags {
    cleanSaveConf = mempty,
    cleanVerbose  = mempty
  }
  mappend a b = CleanFlags {
    cleanSaveConf = combine cleanSaveConf,
    cleanVerbose  = combine cleanVerbose
  }
    where combine field = field a `mappend` field b
988

989
990
991
-- ------------------------------------------------------------
-- * Build flags
-- ------------------------------------------------------------
992

993
994
995
996
997
998
999
1000
1001
1002
1003
data BuildFlags = BuildFlags {
    buildProgramArgs :: [(String, [String])],
    buildVerbose     :: Flag Verbosity
  }
  deriving Show

defaultBuildFlags :: BuildFlags
defaultBuildFlags  = BuildFlags {
    buildProgramArgs = [],
    buildVerbose     = Flag normal
  }
1004

1005
1006
buildCommand :: ProgramConfiguration -> CommandUI BuildFlags
buildCommand progConf = makeCommand name shortDesc longDesc defaultBuildFlags options
1007
  where
1008
1009
1010
1011
1012
    name       = "build"
    shortDesc  = "Make this package ready for installation."
    longDesc   = Nothing
    options showOrParseArgs =
      optionVerbose buildVerbose (\v flags -> flags { buildVerbose = v })
1013

1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
      : programConfigurationOptions progConf showOrParseArgs
          buildProgramArgs (\v flags -> flags { buildProgramArgs = v})

emptyBuildFlags :: BuildFlags
emptyBuildFlags = mempty

instance Monoid BuildFlags where
  mempty = BuildFlags {
    buildProgramArgs = mempty,
    buildVerbose     = mempty
  }
  mappend a b = BuildFlags {
    buildProgramArgs = combine buildProgramArgs,
    buildVerbose     = combine buildVerbose
  }
    where combine field = field a `mappend` field b
1030

1031
1032
1033
1034
1035
1036
1037
1038
1039
-- ------------------------------------------------------------
-- * Makefile flags
-- ------------------------------------------------------------

data MakefileFlags = MakefileFlags {
    makefileFile    :: Flag FilePath,
    makefileVerbose :: Flag Verbosity
  }
  deriving Show
1040

1041
1042
1043
1044
1045
1046
1047
1048
defaultMakefileFlags :: MakefileFlags
defaultMakefileFlags  = MakefileFlags {
    makefileFile    = NoFlag,
    makefileVerbose = Flag normal
  }

makefileCommand :: CommandUI MakefileFlags
makefileCommand = makeCommand name shortDesc longDesc defaultMakefileFlags options
1049
  where
1050
1051
    name       = "makefile"
    shortDesc  = "Generate a makefile (only for GHC libraries)."
1052
1053
    longDesc   = Nothing
    options _  =
1054
      [optionVerbose makefileVerbose (\v flags -> flags { makefileVerbose = v })
1055

1056
1057
1058
1059
      ,option "f" ["file"]
         "Filename to use (default: Makefile)."
         makefileFile (\f flags -> flags { makefileFile = f })
         (reqArgFlag "PATH")
1060
1061
      ]

1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
emptyMakefileFlags :: MakefileFlags
emptyMakefileFlags  = mempty

instance Monoid MakefileFlags where
  mempty = MakefileFlags {
    makefileFile    = mempty,
    makefileVerbose = mempty
  }
  mappend a b = MakefileFlags {
    makefileFile    = combine makefileFile,
    makefileVerbose = combine makefileVerbose
  }
    where combine field = field a `mappend` field b

-- ------------------------------------------------------------
-- * Test flags
-- ------------------------------------------------------------
1079

1080
1081
testCommand :: CommandUI ()
testCommand = makeCommand name shortDesc longDesc () options
1082
  where
1083
1084
    name       = "test"
    shortDesc  = "Run the test suite, if any (configure with UserHooks)."
1085
    longDesc   = Nothing
1086
    options _  = []
1087

1088
1089
1090
-- ------------------------------------------------------------
-- * Shared options utils
-- ------------------------------------------------------------
1091

1092
1093
1094
1095
1096
1097
1098
programFlagsDescription :: ProgramConfiguration -> String
programFlagsDescription progConf =
     "The flags --with-PROG and --PROG-option(s) can be used with"
  ++ " the following programs:"
  ++ (concatMap ("\n  "++) . wrapText 77 . sort)
     [ programName prog | (prog, _) <- knownPrograms progConf ]
  ++ "\n"
1099

1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
programConfigurationPaths
  :: ProgramConfiguration
  -> ShowOrParseArgs
  -> (flags -> [(String, FilePath)])
  -> ([(String, FilePath)] -> (flags -> flags))
  -> [Option flags]
programConfigurationPaths progConf showOrParseArgs get set =
  case showOrParseArgs of
    -- we don't want a verbose help text list so we just show a generic one:
    ShowArgs  -> [withProgramPath "PROG"]
    ParseArgs -> map (withProgramPath . programName . fst) (knownPrograms progConf)
  where
    withProgramPath prog =
      option "" ["with-" ++ prog]
        ("give the path to " ++ prog)
        get set
        (reqArg "PATH" (\path -> [(prog, path)])
          (\progPaths -> [ path | (prog', path) <- progPaths, prog==prog' ]))

programConfigurationOptions
  :: ProgramConfiguration
  -> ShowOrParseArgs
  -> (flags -> [(String, [String])])
  -> ([(String, [String])] -> (flags -> flags))
  -> [Option flags]
programConfigurationOptions progConf showOrParseArgs get set =
  case showOrParseArgs of
    -- we don't want a verbose help text list so we just show a generic one:
    ShowArgs  -> [programOptions  "PROG", programOption   "PROG"]
    ParseArgs -> map (programOptions . programName . fst) (knownPrograms progConf)
              ++ map (programOption  . programName . fst) (knownPrograms progConf)
  where
    programOptions prog =
      option "" [prog ++ "-options"]
        ("give extra options to " ++ prog)
        get set
        (reqArg "OPTS" (\args -> [(prog, splitArgs args)]) (const []))

    programOption prog =
      option "" [prog ++ "-option"]
        ("give an extra option to " ++ prog ++
         " (no need to quote options containing spaces)")
        get set
        (reqArg "OPT" (\arg -> [(prog, [arg])])
           (\progArgs -> concat [ args | (prog', args) <- progArgs, prog==prog' ]))
                
1146
1147
1148
1149
1150

-- ------------------------------------------------------------
-- * GetOpt Utils
-- ------------------------------------------------------------

1151
1152
1153
trueArg, falseArg :: (b -> Flag Bool) -> (Flag Bool -> b -> b) -> ArgDescr b
trueArg  = noArg (Flag True) (\f -> case f of Flag True  -> True; _ -> False)
falseArg = noArg (Flag False) (\f -> case f of Flag False -> True; _ -> False)
1154

1155
1156
1157
reqArgFlag :: String
           -> (b -> Flag String) -> (Flag String -> b -> b) -> ArgDescr b
reqArgFlag name = reqArg name Flag flagToList
1158

1159
1160
1161
1162
optionVerbose :: (flags -> Flag Verbosity)
              -> (Flag Verbosity -> flags -> flags)
              -> Option flags
optionVerbose get set =
1163
1164
  option "v" ["verbose"]
    "Control verbosity (n is 0--3, default verbosity level is 1)"
1165
1166
1167
1168
1169
    get set
    (optArg "n" (Flag . flagToVerbosity)
                (\f -> case f of
                         Flag v -> [Just (showForCabal v)]
                         _      -> []))
1170
1171

-- ------------------------------------------------------------
1172
-- * Other Utils
1173
1174
1175
1176
-- ------------------------------------------------------------

-- | Arguments to pass to a @configure@ script, e.g. generated by
-- @autoconf@.
1177
1178
configureArgs :: Bool -> ConfigFlags -> [String]
configureArgs bcHack flags
1179
1180
1181
1182
1183
1184
1185
1186
  = hc_flag
 ++ optFlag  "with-hc-pkg" configHcPkg
 ++ optFlag' "prefix"      prefix
 ++ optFlag' "bindir"      bindir
 ++ optFlag' "libdir"      libdir
 ++ optFlag' "libexecdir"  libexecdir
 ++ optFlag' "datadir"     datadir
 ++ configConfigureArgs flags
1187
1188
  where
        hc_flag = case (configHcFlavor flags, configHcPath flags) of
1189
1190
1191
1192
1193
1194
1195
                        (_, Flag hc_path) -> [hc_flag_name ++ hc_path]
                        (Flag hc, NoFlag) -> [hc_flag_name ++ showHC hc]
                        (NoFlag,NoFlag)   -> []
        hc_flag_name
            --TODO kill off thic bc hack when defaultUserHooks is removed.
            | bcHack    = "--with-hc="
	    | otherwise = "--with-compiler="
1196
        optFlag name config_field = case config_field flags of
1197
1198
1199
1200
1201
                        Flag p -> ["--" ++ name ++ "=" ++ p]
                        NoFlag -> []
        optFlag' name config_field = optFlag name (fmap fromPathTemplate
                                                 . config_field
                                                 . configInstallDirs)
1202
1203
1204

        showHC GHC = "ghc"
        showHC NHC = "nhc98"
ekarttun's avatar
ekarttun committed
1205
        showHC JHC = "jhc"
1206
1207
1208
        showHC Hugs = "hugs"
        showHC c    = "unknown compiler: " ++ (show c)

1209
-- | Helper function to split a string into a list of arguments.
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
-- It's supposed to handle quoted things sensibly, eg:
--
-- > splitArgs "--foo=\"C:\Program Files\Bar\" --baz"
-- >   = ["--foo=C:\Program Files\Bar", "--baz"]
--
splitArgs :: String -> [String]
splitArgs  = space []
  where
    space :: String -> String -> [String]
    space w []      = word w []
    space w ( c :s)
        | isSpace c = word w (space [] s)
    space w ('"':s) = string w s
    space w s       = nonstring w s

    string :: String -> String -> [String]
    string w []      = word w []
    string w ('"':s) = space w s
    string w ( c :s) = string (c:w) s

    nonstring :: String -> String -> [String]
    nonstring w  []      = word w []
    nonstring w  ('"':s) = string w s
    nonstring w  ( c :s) = space (c:w) s

    word [] s = s
    word w  s = reverse w : s

md9ms's avatar
md9ms committed
1238
-- The test cases kinda have to be rewritten from the ground up... :/
1239
--hunitTests :: [Test]
md9ms's avatar
md9ms committed
1240
--hunitTests =
1241
--    let m = [("ghc", GHC), ("nhc98", NHC), ("hugs", Hugs)]
md9ms's avatar
md9ms committed
1242
--        (flags, commands', unkFlags, ers)
1243
--               = getOpt Permute options ["configure", "foobar", "--prefix=/foo", "--ghc", "--nhc98", "--hugs", "--with-compiler=/comp", "--unknown1", "--unknown2", "--install-prefix=/foo", "--user", "--global"]
md9ms's avatar
md9ms committed
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
--       in  [TestLabel "very basic option parsing" $ TestList [
--                 "getOpt flags" ~: "failed" ~:
--                 [Prefix "/foo", GhcFlag, NhcFlag, HugsFlag,
--                  WithCompiler "/comp", InstPrefix "/foo", UserFlag, GlobalFlag]
--                 ~=? flags,
--                 "getOpt commands" ~: "failed" ~: ["configure", "foobar"] ~=? commands',
--                 "getOpt unknown opts" ~: "failed" ~:
--                      ["--unknown1", "--unknown2"] ~=? unkFlags,
--                 "getOpt errors" ~: "failed" ~: [] ~=? ers],
--
--               TestLabel "test location of various compilers" $ TestList
--               ["configure parsing for prefix and compiler flag" ~: "failed" ~:
--                    (Right (ConfigCmd (Just comp, Nothing, Just "/usr/local"), []))
--                   ~=? (parseArgs ["--prefix=/usr/local", "--"++name, "configure"])
--                   | (name, comp) <- m],
--
--               TestLabel "find the package tool" $ TestList
--               ["configure parsing for prefix comp flag, withcompiler" ~: "failed" ~:
--                    (Right (ConfigCmd (Just comp, Just "/foo/comp", Just "/usr/local"), []))
--                   ~=? (parseArgs ["--prefix=/usr/local", "--"++name,
--                                   "--with-compiler=/foo/comp", "configure"])
--                   | (name, comp) <- m],
--
--               TestLabel "simpler commands" $ TestList
--               [flag ~: "failed" ~: (Right (flagCmd, [])) ~=? (parseArgs [flag])
--                   | (flag, flagCmd) <- [("build", BuildCmd),
--                                         ("install", InstallCmd Nothing False),
--                                         ("sdist", SDistCmd),
--                                         ("register", RegisterCmd False)]
--                  ]
--               ]

ijones's avatar
ijones committed
1276
1277
1278
1279
1280
{- Testing ideas:
   * IO to look for hugs and hugs-pkg (which hugs, etc)
   * quickCheck to test permutations of arguments
   * what other options can we over-ride with a command-line flag?
-}