Setup.hs 68.6 KB
Newer Older
1
2
-----------------------------------------------------------------------------
-- |
3
-- Module      :  Distribution.Client.Setup
4
5
6
7
8
9
10
11
12
-- Copyright   :  (c) David Himmelstrup 2005
-- License     :  BSD-like
--
-- Maintainer  :  lemmih@gmail.com
-- Stability   :  provisional
-- Portability :  portable
--
--
-----------------------------------------------------------------------------
13
module Distribution.Client.Setup
14
    ( globalCommand, GlobalFlags(..), defaultGlobalFlags, globalRepos
15
    , configureCommand, ConfigFlags(..), filterConfigureFlags
16
17
    , configureExCommand, ConfigExFlags(..), defaultConfigExFlags
                        , configureExOptions
18
19
    , buildCommand, BuildFlags(..), BuildExFlags(..), SkipAddSourceDepsCheck(..)
    , testCommand, benchmarkCommand
20
    , installCommand, InstallFlags(..), installOptions, defaultInstallFlags
21
    , listCommand, ListFlags(..)
Duncan Coutts's avatar
Duncan Coutts committed
22
    , updateCommand
ijones's avatar
ijones committed
23
    , upgradeCommand
24
    , infoCommand, InfoFlags(..)
25
    , fetchCommand, FetchFlags(..)
26
    , freezeCommand, FreezeFlags(..)
27
    , getCommand, unpackCommand, GetFlags(..)
28
    , checkCommand
29
    , formatCommand
30
    , uploadCommand, UploadFlags(..)
31
    , reportCommand, ReportFlags(..)
refold's avatar
refold committed
32
    , runCommand
33
    , initCommand, IT.InitFlags(..)
34
    , sdistCommand, SDistFlags(..), SDistExFlags(..), ArchiveFormat(..)
35
    , win32SelfUpgradeCommand, Win32SelfUpgradeFlags(..)
refold's avatar
refold committed
36
    , sandboxCommand, defaultSandboxLocation, SandboxFlags(..)
37
    , execCommand, ExecFlags(..)
Duncan Coutts's avatar
Duncan Coutts committed
38
39

    , parsePackageArgs
40
41
42
    --TODO: stop exporting these:
    , showRepo
    , parseRepo
43
44
    ) where

45
import Distribution.Client.Types
46
         ( Username(..), Password(..), Repo(..), RemoteRepo(..), LocalRepo(..) )
47
48
import Distribution.Client.BuildReports.Types
         ( ReportLevel(..) )
49
import Distribution.Client.Dependency.Types
50
         ( AllowNewer(..), PreSolver(..) )
51
52
import qualified Distribution.Client.Init.Types as IT
         ( InitFlags(..), PackageType(..) )
53
54
import Distribution.Client.Targets
         ( UserConstraint, readUserConstraint )
55

56
import Distribution.Simple.Compiler (PackageDB)
57
58
import Distribution.Simple.Program
         ( defaultProgramConfiguration )
59
60
import Distribution.Simple.Command hiding (boolOpt, boolOpt')
import qualified Distribution.Simple.Command as Command
Duncan Coutts's avatar
Duncan Coutts committed
61
import qualified Distribution.Simple.Setup as Cabal
62
import Distribution.Simple.Setup
63
64
         ( ConfigFlags(..), BuildFlags(..), TestFlags(..), BenchmarkFlags(..)
         , SDistFlags(..), HaddockFlags(..)
65
         , readPackageDbList, showPackageDbList
66
         , Flag(..), toFlag, fromFlag, flagToMaybe, flagToList
67
         , optionVerbosity, boolOpt, boolOpt', trueArg, falseArg, optionNumJobs )
68
import Distribution.Simple.InstallDirs
69
70
         ( PathTemplate, InstallDirs(sysconfdir)
         , toPathTemplate, fromPathTemplate )
71
import Distribution.Version
Duncan Coutts's avatar
Duncan Coutts committed
72
         ( Version(Version), anyVersion, thisVersion )
73
import Distribution.Package
74
         ( PackageIdentifier, packageName, packageVersion, Dependency(..) )
75
76
import Distribution.PackageDescription
         ( RepoKind(..) )
77
import Distribution.Text
78
         ( Text(..), display )
79
import Distribution.ReadE
80
         ( ReadE(..), readP_to_E, succeedReadE )
81
import qualified Distribution.Compat.ReadP as Parse
82
         ( ReadP, readP_to_S, readS_to_P, char, munch1, pfail, sepBy1, (+++) )
83
84
import Distribution.Verbosity
         ( Verbosity, normal )
85
86
import Distribution.Simple.Utils
         ( wrapText )
87

88
89
import Data.Char
         ( isSpace, isAlphaNum )
90
91
import Data.List
         ( intercalate )
92
import Data.Maybe
93
         ( listToMaybe, maybeToList, fromMaybe )
94
95
96
97
98
99
100
101
import Data.Monoid
         ( Monoid(..) )
import Control.Monad
         ( liftM )
import System.FilePath
         ( (</>) )
import Network.URI
         ( parseAbsoluteURI, uriToString )
102

103
104
105
106
107
108
-- ------------------------------------------------------------
-- * Global flags
-- ------------------------------------------------------------

-- | Flags that apply at the top level, not to any sub-command.
data GlobalFlags = GlobalFlags {
109
110
111
112
113
114
115
116
    globalVersion           :: Flag Bool,
    globalNumericVersion    :: Flag Bool,
    globalConfigFile        :: Flag FilePath,
    globalSandboxConfigFile :: Flag FilePath,
    globalRemoteRepos       :: [RemoteRepo],     -- ^ Available Hackage servers.
    globalCacheDir          :: Flag FilePath,
    globalLocalRepos        :: [FilePath],
    globalLogsDir           :: Flag FilePath,
117
    globalWorldFile         :: Flag FilePath,
118
119
    globalRequireSandbox    :: Flag Bool,
    globalIgnoreSandbox     :: Flag Bool
120
  }
Duncan Coutts's avatar
Duncan Coutts committed
121

122
123
defaultGlobalFlags :: GlobalFlags
defaultGlobalFlags  = GlobalFlags {
124
125
126
127
    globalVersion           = Flag False,
    globalNumericVersion    = Flag False,
    globalConfigFile        = mempty,
    globalSandboxConfigFile = mempty,
128
    globalRemoteRepos       = mempty,
129
130
131
    globalCacheDir          = mempty,
    globalLocalRepos        = mempty,
    globalLogsDir           = mempty,
132
    globalWorldFile         = mempty,
133
134
    globalRequireSandbox    = Flag False,
    globalIgnoreSandbox     = Flag False
135
136
137
138
139
140
  }

globalCommand :: CommandUI GlobalFlags
globalCommand = CommandUI {
    commandName         = "",
    commandSynopsis     = "",
141
142
143
144
    commandUsage        = \_ ->
         "This program is the command line interface "
           ++ "to the Haskell Cabal infrastructure.\n"
      ++ "See http://www.haskell.org/cabal/ for more information.\n",
145
    commandDescription  = Just $ \pname ->
146
147
148
149
150
151
         "For more information about a command use:\n"
      ++ "  " ++ pname ++ " COMMAND --help\n\n"
      ++ "To install Cabal packages from hackage use:\n"
      ++ "  " ++ pname ++ " install foo [--dry-run]\n\n"
      ++ "Occasionally you need to update the list of available packages:\n"
      ++ "  " ++ pname ++ " update\n",
152
    commandDefaultFlags = mempty,
153
    commandOptions      = \showOrParseArgs ->
154
      (case showOrParseArgs of ShowArgs -> take 6; ParseArgs -> id)
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
      [option ['V'] ["version"]
         "Print version information"
         globalVersion (\v flags -> flags { globalVersion = v })
         trueArg

      ,option [] ["numeric-version"]
         "Print just the version number"
         globalNumericVersion (\v flags -> flags { globalNumericVersion = v })
         trueArg

      ,option [] ["config-file"]
         "Set an alternate location for the config file"
         globalConfigFile (\v flags -> flags { globalConfigFile = v })
         (reqArgFlag "FILE")

170
171
172
173
174
175
      ,option [] ["sandbox-config-file"]
         "Set an alternate location for the sandbox config file \
         \(default: './cabal.sandbox.config')"
         globalConfigFile (\v flags -> flags { globalSandboxConfigFile = v })
         (reqArgFlag "FILE")

176
      ,option [] ["require-sandbox"]
Mikhail Glushenkov's avatar
Mikhail Glushenkov committed
177
         "requiring the presence of a sandbox for sandbox-aware commands"
178
179
180
         globalRequireSandbox (\v flags -> flags { globalRequireSandbox = v })
         (boolOpt' ([], ["require-sandbox"]) ([], ["no-require-sandbox"]))

181
182
183
184
185
      ,option [] ["ignore-sandbox"]
         "Ignore any existing sandbox"
         globalIgnoreSandbox (\v flags -> flags { globalIgnoreSandbox = v })
         trueArg

186
187
188
189
190
191
192
193
194
195
196
197
198
199
      ,option [] ["remote-repo"]
         "The name and url for a remote repository"
         globalRemoteRepos (\v flags -> flags { globalRemoteRepos = v })
         (reqArg' "NAME:URL" (maybeToList . readRepo) (map showRepo))

      ,option [] ["remote-repo-cache"]
         "The location where downloads from all remote repos are cached"
         globalCacheDir (\v flags -> flags { globalCacheDir = v })
         (reqArgFlag "DIR")

      ,option [] ["local-repo"]
         "The location of a local repository"
         globalLocalRepos (\v flags -> flags { globalLocalRepos = v })
         (reqArg' "DIR" (\x -> [x]) id)
200

201
202
203
204
205
      ,option [] ["logs-dir"]
         "The location to put log files"
         globalLogsDir (\v flags -> flags { globalLogsDir = v })
         (reqArgFlag "DIR")

206
207
208
209
      ,option [] ["world-file"]
         "The location of the world file"
         globalWorldFile (\v flags -> flags { globalWorldFile = v })
         (reqArgFlag "FILE")
210
211
212
213
214
      ]
  }

instance Monoid GlobalFlags where
  mempty = GlobalFlags {
215
216
217
218
219
220
221
222
    globalVersion           = mempty,
    globalNumericVersion    = mempty,
    globalConfigFile        = mempty,
    globalSandboxConfigFile = mempty,
    globalRemoteRepos       = mempty,
    globalCacheDir          = mempty,
    globalLocalRepos        = mempty,
    globalLogsDir           = mempty,
223
    globalWorldFile         = mempty,
224
225
    globalRequireSandbox    = mempty,
    globalIgnoreSandbox     = mempty
226
227
  }
  mappend a b = GlobalFlags {
228
229
230
231
232
233
234
235
    globalVersion           = combine globalVersion,
    globalNumericVersion    = combine globalNumericVersion,
    globalConfigFile        = combine globalConfigFile,
    globalSandboxConfigFile = combine globalConfigFile,
    globalRemoteRepos       = combine globalRemoteRepos,
    globalCacheDir          = combine globalCacheDir,
    globalLocalRepos        = combine globalLocalRepos,
    globalLogsDir           = combine globalLogsDir,
236
    globalWorldFile         = combine globalWorldFile,
237
238
    globalRequireSandbox    = combine globalRequireSandbox,
    globalIgnoreSandbox     = combine globalIgnoreSandbox
Duncan Coutts's avatar
Duncan Coutts committed
239
  }
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
    where combine field = field a `mappend` field b

globalRepos :: GlobalFlags -> [Repo]
globalRepos globalFlags = remoteRepos ++ localRepos
  where
    remoteRepos =
      [ Repo (Left remote) cacheDir
      | remote <- globalRemoteRepos globalFlags
      , let cacheDir = fromFlag (globalCacheDir globalFlags)
                   </> remoteRepoName remote ]
    localRepos =
      [ Repo (Right LocalRepo) local
      | local <- globalLocalRepos globalFlags ]

-- ------------------------------------------------------------
-- * Config flags
-- ------------------------------------------------------------
Duncan Coutts's avatar
Duncan Coutts committed
257

258
configureCommand :: CommandUI ConfigFlags
259
configureCommand = (Cabal.configureCommand defaultProgramConfiguration) {
260
    commandDefaultFlags = mempty
Duncan Coutts's avatar
Duncan Coutts committed
261
262
  }

263
264
265
configureOptions ::  ShowOrParseArgs -> [OptionField ConfigFlags]
configureOptions = commandOptions configureCommand

266
filterConfigureFlags :: ConfigFlags -> Version -> ConfigFlags
267
filterConfigureFlags flags cabalLibVersion
268
  | cabalLibVersion >= Version [1,19,2] [] = flags_latest
269
270
271
  | cabalLibVersion <  Version [1,3,10] [] = flags_1_3_10
  | cabalLibVersion <  Version [1,10,0] [] = flags_1_10_0
  | cabalLibVersion <  Version [1,14,0] [] = flags_1_14_0
272
  | cabalLibVersion <  Version [1,18,0] [] = flags_1_18_0
273
  | cabalLibVersion <  Version [1,19,1] [] = flags_1_19_0
274
  | cabalLibVersion <  Version [1,19,2] [] = flags_1_19_1
275
  | otherwise = flags_latest
276
  where
277
    -- Cabal >= 1.19.1 uses '--dependency' and does not need '--constraint'.
278
279
    flags_latest = flags        { configConstraints = [] }

280
281
282
283
284
    -- Cabal < 1.19.2 doesn't know about '--exact-configuration'.
    flags_1_19_1 = flags_latest { configExactConfiguration = NoFlag }
    -- Cabal < 1.19.1 uses '--constraint' instead of '--dependency'.
    flags_1_19_0 = flags_1_19_1 { configDependencies = []
                                , configConstraints  = configConstraints flags }
285
    -- Cabal < 1.18.0 doesn't know about --extra-prog-path and --sysconfdir.
286
    flags_1_18_0 = flags_1_19_0 { configProgramPathExtra = []
287
288
                                , configInstallDirs = configInstallDirs_1_18_0}
    configInstallDirs_1_18_0 = (configInstallDirs flags) { sysconfdir = NoFlag }
289
    -- Cabal < 1.14.0 doesn't know about '--disable-benchmarks'.
290
    flags_1_14_0 = flags_1_18_0 { configBenchmarks  = NoFlag }
291
    -- Cabal < 1.10.0 doesn't know about '--disable-tests'.
292
    flags_1_10_0 = flags_1_14_0 { configTests       = NoFlag }
293
    -- Cabal < 1.3.10 does not grok the '--constraints' flag.
294
    flags_1_3_10 = flags_1_10_0 { configConstraints = [] }
295

296
297
298
299
300
301
302
303
-- ------------------------------------------------------------
-- * Config extra flags
-- ------------------------------------------------------------

-- | cabal configure takes some extra flags beyond runghc Setup configure
--
data ConfigExFlags = ConfigExFlags {
    configCabalVersion :: Flag Version,
304
    configExConstraints:: [UserConstraint],
305
    configPreferences  :: [Dependency],
306
307
    configSolver       :: Flag PreSolver,
    configAllowNewer   :: Flag AllowNewer
308
309
310
  }

defaultConfigExFlags :: ConfigExFlags
311
312
defaultConfigExFlags = mempty { configSolver     = Flag defaultSolver
                              , configAllowNewer = Flag AllowNewerNone }
313
314
315
316
317

configureExCommand :: CommandUI (ConfigFlags, ConfigExFlags)
configureExCommand = configureCommand {
    commandDefaultFlags = (mempty, defaultConfigExFlags),
    commandOptions      = \showOrParseArgs ->
318
         liftOptions fst setFst
319
         (filter ((`notElem` ["constraint", "dependency", "exact-configuration"])
320
                  . optionName) $ configureOptions  showOrParseArgs)
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
      ++ liftOptions snd setSnd (configureExOptions showOrParseArgs)
  }
  where
    setFst a (_,b) = (a,b)
    setSnd b (a,_) = (a,b)

configureExOptions ::  ShowOrParseArgs -> [OptionField ConfigExFlags]
configureExOptions _showOrParseArgs =
  [ option [] ["cabal-lib-version"]
      ("Select which version of the Cabal lib to use to build packages "
      ++ "(useful for testing).")
      configCabalVersion (\v flags -> flags { configCabalVersion = v })
      (reqArg "VERSION" (readP_to_E ("Cannot parse cabal lib version: "++)
                                    (fmap toFlag parse))
                        (map display . flagToList))
336
337
338
339
340
341
  , option [] ["constraint"]
      "Specify constraints on a package (version, installed/source, flags)"
      configExConstraints (\v flags -> flags { configExConstraints = v })
      (reqArg "CONSTRAINT"
              (fmap (\x -> [x]) (ReadE readUserConstraint))
              (map display))
342
343
344
345

  , option [] ["preference"]
      "Specify preferences (soft constraints) on the version of a package"
      configPreferences (\v flags -> flags { configPreferences = v })
346
347
348
349
      (reqArg "CONSTRAINT"
              (readP_to_E (const "dependency expected")
                          (fmap (\x -> [x]) parse))
              (map display))
350
351

  , optionSolver configSolver (\v flags -> flags { configSolver = v })
352
353
354
355
356
357
358
359

  , option [] ["allow-newer"]
    "Ignore upper bounds in dependencies on some or all packages."
    configAllowNewer (\v flags -> flags { configAllowNewer = v})
    (optArg "PKGS"
     (fmap Flag allowNewerParser) (Flag AllowNewerAll)
     allowNewerPrinter)

360
361
362
363
364
  ]

instance Monoid ConfigExFlags where
  mempty = ConfigExFlags {
    configCabalVersion = mempty,
365
    configExConstraints= mempty,
366
    configPreferences  = mempty,
367
368
    configSolver       = mempty,
    configAllowNewer   = mempty
369
370
371
  }
  mappend a b = ConfigExFlags {
    configCabalVersion = combine configCabalVersion,
372
    configExConstraints= combine configExConstraints,
373
    configPreferences  = combine configPreferences,
374
375
    configSolver       = combine configSolver,
    configAllowNewer   = combine configAllowNewer
376
377
378
  }
    where combine field = field a `mappend` field b

ttuegel's avatar
ttuegel committed
379
380
381
382
-- ------------------------------------------------------------
-- * Build flags
-- ------------------------------------------------------------

383
384
385
386
387
388
389
390
391
392
data SkipAddSourceDepsCheck =
  SkipAddSourceDepsCheck | DontSkipAddSourceDepsCheck
  deriving Eq

data BuildExFlags = BuildExFlags {
  buildOnly     :: Flag SkipAddSourceDepsCheck
}

buildExOptions :: ShowOrParseArgs -> [OptionField BuildExFlags]
buildExOptions _showOrParseArgs =
393
  option [] ["only"]
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
  "Don't reinstall add-source dependencies (sandbox-only)"
  buildOnly (\v flags -> flags { buildOnly = v })
  (noArg (Flag SkipAddSourceDepsCheck))

  : []

buildCommand :: CommandUI (BuildFlags, BuildExFlags)
buildCommand = parent {
    commandDefaultFlags = (commandDefaultFlags parent, mempty),
    commandOptions      =
      \showOrParseArgs -> liftOptions fst setFst
                          (commandOptions parent showOrParseArgs)
                          ++
                          liftOptions snd setSnd (buildExOptions showOrParseArgs)
  }
  where
    setFst a (_,b) = (a,b)
    setSnd b (a,_) = (a,b)

    parent = Cabal.buildCommand defaultProgramConfiguration

instance Monoid BuildExFlags where
  mempty = BuildExFlags {
    buildOnly    = mempty
  }
  mappend a b = BuildExFlags {
    buildOnly    = combine buildOnly
  }
    where combine field = field a `mappend` field b

-- ------------------------------------------------------------
-- * Test command
-- ------------------------------------------------------------

428
testCommand :: CommandUI (TestFlags, BuildFlags, BuildExFlags)
429
testCommand = parent {
430
431
  commandDefaultFlags = (commandDefaultFlags parent,
                         Cabal.defaultBuildFlags, mempty),
432
  commandOptions      =
433
    \showOrParseArgs -> liftOptions get1 set1
434
435
                        (commandOptions parent showOrParseArgs)
                        ++
436
437
438
439
                        liftOptions get2 set2
                        (Cabal.buildOptions progConf showOrParseArgs)
                        ++
                        liftOptions get3 set3 (buildExOptions showOrParseArgs)
440
441
  }
  where
442
443
444
    get1 (a,_,_) = a; set1 a (_,b,c) = (a,b,c)
    get2 (_,b,_) = b; set2 b (a,_,c) = (a,b,c)
    get3 (_,_,c) = c; set3 c (a,b,_) = (a,b,c)
445

446
447
    parent   = Cabal.testCommand
    progConf = defaultProgramConfiguration
448
449
450
451
452

-- ------------------------------------------------------------
-- * Bench command
-- ------------------------------------------------------------

453
benchmarkCommand :: CommandUI (BenchmarkFlags, BuildFlags, BuildExFlags)
454
benchmarkCommand = parent {
455
456
  commandDefaultFlags = (commandDefaultFlags parent,
                         Cabal.defaultBuildFlags, mempty),
457
  commandOptions      =
458
    \showOrParseArgs -> liftOptions get1 set1
459
460
                        (commandOptions parent showOrParseArgs)
                        ++
461
462
463
464
                        liftOptions get2 set2
                        (Cabal.buildOptions progConf showOrParseArgs)
                        ++
                        liftOptions get3 set3 (buildExOptions showOrParseArgs)
ttuegel's avatar
ttuegel committed
465
  }
466
  where
467
468
469
    get1 (a,_,_) = a; set1 a (_,b,c) = (a,b,c)
    get2 (_,b,_) = b; set2 b (a,_,c) = (a,b,c)
    get3 (_,_,c) = c; set3 c (a,b,_) = (a,b,c)
470

471
472
    parent   = Cabal.benchmarkCommand
    progConf = defaultProgramConfiguration
ttuegel's avatar
ttuegel committed
473

474
-- ------------------------------------------------------------
475
-- * Fetch command
476
-- ------------------------------------------------------------
477

478
479
480
481
data FetchFlags = FetchFlags {
--    fetchOutput    :: Flag FilePath,
      fetchDeps      :: Flag Bool,
      fetchDryRun    :: Flag Bool,
482
      fetchSolver           :: Flag PreSolver,
483
484
485
      fetchMaxBackjumps     :: Flag Int,
      fetchReorderGoals     :: Flag Bool,
      fetchIndependentGoals :: Flag Bool,
486
      fetchShadowPkgs       :: Flag Bool,
Andres Löh's avatar
Andres Löh committed
487
      fetchStrongFlags      :: Flag Bool,
488
489
490
491
492
493
494
495
      fetchVerbosity :: Flag Verbosity
    }

defaultFetchFlags :: FetchFlags
defaultFetchFlags = FetchFlags {
--  fetchOutput    = mempty,
    fetchDeps      = toFlag True,
    fetchDryRun    = toFlag False,
496
497
    fetchSolver           = Flag defaultSolver,
    fetchMaxBackjumps     = Flag defaultMaxBackjumps,
498
    fetchReorderGoals     = Flag False,
499
    fetchIndependentGoals = Flag False,
500
    fetchShadowPkgs       = Flag False,
Andres Löh's avatar
Andres Löh committed
501
    fetchStrongFlags      = Flag False,
502
503
504
505
    fetchVerbosity = toFlag normal
   }

fetchCommand :: CommandUI FetchFlags
Duncan Coutts's avatar
Duncan Coutts committed
506
507
fetchCommand = CommandUI {
    commandName         = "fetch",
508
    commandSynopsis     = "Downloads packages for later installation.",
Duncan Coutts's avatar
Duncan Coutts committed
509
    commandDescription  = Nothing,
refold's avatar
refold committed
510
    commandUsage        = usagePackages "fetch",
511
    commandDefaultFlags = defaultFetchFlags,
512
    commandOptions      = \ showOrParseArgs -> [
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
         optionVerbosity fetchVerbosity (\v flags -> flags { fetchVerbosity = v })

--     , option "o" ["output"]
--         "Put the package(s) somewhere specific rather than the usual cache."
--         fetchOutput (\v flags -> flags { fetchOutput = v })
--         (reqArgFlag "PATH")

       , option [] ["dependencies", "deps"]
           "Resolve and fetch dependencies (default)"
           fetchDeps (\v flags -> flags { fetchDeps = v })
           trueArg

       , option [] ["no-dependencies", "no-deps"]
           "Ignore dependencies"
           fetchDeps (\v flags -> flags { fetchDeps = v })
           falseArg

       , option [] ["dry-run"]
           "Do not install anything, only print what would be installed."
           fetchDryRun (\v flags -> flags { fetchDryRun = v })
           trueArg
534
535
536
537

       ] ++

       optionSolver      fetchSolver           (\v flags -> flags { fetchSolver           = v }) :
538
539
       optionSolverFlags showOrParseArgs
                         fetchMaxBackjumps     (\v flags -> flags { fetchMaxBackjumps     = v })
540
541
                         fetchReorderGoals     (\v flags -> flags { fetchReorderGoals     = v })
                         fetchIndependentGoals (\v flags -> flags { fetchIndependentGoals = v })
542
                         fetchShadowPkgs       (\v flags -> flags { fetchShadowPkgs       = v })
Andres Löh's avatar
Andres Löh committed
543
                         fetchStrongFlags      (\v flags -> flags { fetchStrongFlags      = v })
544

Duncan Coutts's avatar
Duncan Coutts committed
545
546
  }

547
548
549
550
551
552
-- ------------------------------------------------------------
-- * Freeze command
-- ------------------------------------------------------------

data FreezeFlags = FreezeFlags {
      freezeDryRun           :: Flag Bool,
553
554
      freezeTests            :: Flag Bool,
      freezeBenchmarks       :: Flag Bool,
555
556
557
558
559
      freezeSolver           :: Flag PreSolver,
      freezeMaxBackjumps     :: Flag Int,
      freezeReorderGoals     :: Flag Bool,
      freezeIndependentGoals :: Flag Bool,
      freezeShadowPkgs       :: Flag Bool,
Andres Löh's avatar
Andres Löh committed
560
      freezeStrongFlags      :: Flag Bool,
561
562
563
564
565
566
      freezeVerbosity        :: Flag Verbosity
    }

defaultFreezeFlags :: FreezeFlags
defaultFreezeFlags = FreezeFlags {
    freezeDryRun           = toFlag False,
567
568
    freezeTests            = toFlag False,
    freezeBenchmarks       = toFlag False,
569
570
    freezeSolver           = Flag defaultSolver,
    freezeMaxBackjumps     = Flag defaultMaxBackjumps,
571
    freezeReorderGoals     = Flag False,
572
573
    freezeIndependentGoals = Flag False,
    freezeShadowPkgs       = Flag False,
Andres Löh's avatar
Andres Löh committed
574
    freezeStrongFlags      = Flag False,
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
    freezeVerbosity        = toFlag normal
   }

freezeCommand :: CommandUI FreezeFlags
freezeCommand = CommandUI {
    commandName         = "freeze",
    commandSynopsis     = "Freeze dependencies.",
    commandDescription  = Nothing,
    commandUsage        = usagePackages "freeze",
    commandDefaultFlags = defaultFreezeFlags,
    commandOptions      = \ showOrParseArgs -> [
         optionVerbosity freezeVerbosity (\v flags -> flags { freezeVerbosity = v })

       , option [] ["dry-run"]
           "Do not freeze anything, only print what would be frozen"
           freezeDryRun (\v flags -> flags { freezeDryRun = v })
           trueArg

593
594
595
596
597
598
599
600
601
602
       , option [] ["tests"]
           "freezing of the dependencies of any tests suites in the package description file."
           freezeTests (\v flags -> flags { freezeTests = v })
           (boolOpt [] [])

       , option [] ["benchmarks"]
           "freezing of the dependencies of any benchmarks suites in the package description file."
           freezeBenchmarks (\v flags -> flags { freezeBenchmarks = v })
           (boolOpt [] [])

603
604
605
606
607
608
609
610
       ] ++

       optionSolver      freezeSolver           (\v flags -> flags { freezeSolver           = v }) :
       optionSolverFlags showOrParseArgs
                         freezeMaxBackjumps     (\v flags -> flags { freezeMaxBackjumps     = v })
                         freezeReorderGoals     (\v flags -> flags { freezeReorderGoals     = v })
                         freezeIndependentGoals (\v flags -> flags { freezeIndependentGoals = v })
                         freezeShadowPkgs       (\v flags -> flags { freezeShadowPkgs       = v })
Andres Löh's avatar
Andres Löh committed
611
                         freezeStrongFlags      (\v flags -> flags { freezeStrongFlags      = v })
612
613
614

  }

615
616
617
618
-- ------------------------------------------------------------
-- * Other commands
-- ------------------------------------------------------------

619
updateCommand  :: CommandUI (Flag Verbosity)
Duncan Coutts's avatar
Duncan Coutts committed
620
621
updateCommand = CommandUI {
    commandName         = "update",
622
    commandSynopsis     = "Updates list of known packages.",
Duncan Coutts's avatar
Duncan Coutts committed
623
    commandDescription  = Nothing,
refold's avatar
refold committed
624
    commandUsage        = usageFlags "update",
625
    commandDefaultFlags = toFlag normal,
626
    commandOptions      = \_ -> [optionVerbosity id const]
Duncan Coutts's avatar
Duncan Coutts committed
627
628
  }

629
upgradeCommand  :: CommandUI (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags)
630
upgradeCommand = configureCommand {
ijones's avatar
ijones committed
631
    commandName         = "upgrade",
632
    commandSynopsis     = "(command disabled, use install instead)",
ijones's avatar
ijones committed
633
    commandDescription  = Nothing,
refold's avatar
refold committed
634
    commandUsage        = usageFlagsOrPackages "upgrade",
635
    commandDefaultFlags = (mempty, mempty, mempty, mempty),
636
    commandOptions      = commandOptions installCommand
ijones's avatar
ijones committed
637
638
  }

Duncan Coutts's avatar
Duncan Coutts committed
639
640
641
642
643
644
645
646
647
648
649
{-
cleanCommand  :: CommandUI ()
cleanCommand = makeCommand name shortDesc longDesc emptyFlags options
  where
    name       = "clean"
    shortDesc  = "Removes downloaded files"
    longDesc   = Nothing
    emptyFlags = ()
    options _  = []
-}

650
651
652
checkCommand  :: CommandUI (Flag Verbosity)
checkCommand = CommandUI {
    commandName         = "check",
653
    commandSynopsis     = "Check the package for common mistakes.",
654
655
    commandDescription  = Nothing,
    commandUsage        = \pname -> "Usage: " ++ pname ++ " check\n",
656
    commandDefaultFlags = toFlag normal,
657
    commandOptions      = \_ -> []
658
659
  }

660
661
662
663
664
665
666
667
668
669
formatCommand  :: CommandUI (Flag Verbosity)
formatCommand = CommandUI {
    commandName         = "format",
    commandSynopsis     = "Reformat the .cabal file using the standard style.",
    commandDescription  = Nothing,
    commandUsage        = \pname -> "Usage: " ++ pname ++ " format [FILE]\n",
    commandDefaultFlags = toFlag normal,
    commandOptions      = \_ -> []
  }

670
runCommand :: CommandUI (BuildFlags, BuildExFlags)
refold's avatar
refold committed
671
672
673
674
675
runCommand = CommandUI {
    commandName         = "run",
    commandSynopsis     = "Runs the compiled executable.",
    commandDescription  = Nothing,
    commandUsage        =
676
677
678
      \pname -> "Usage: " ++ pname
                ++ " run [FLAGS] [EXECUTABLE] [-- EXECUTABLE_FLAGS]\n\n"
                ++ "Flags for run:",
refold's avatar
refold committed
679
    commandDefaultFlags = mempty,
680
681
    commandOptions      =
      \showOrParseArgs -> liftOptions fst setFst
682
                          (commandOptions parent showOrParseArgs)
683
684
685
                          ++
                          liftOptions snd setSnd
                          (buildExOptions showOrParseArgs)
refold's avatar
refold committed
686
687
  }
  where
688
689
690
    setFst a (_,b) = (a,b)
    setSnd b (a,_) = (a,b)

691
    parent = Cabal.buildCommand defaultProgramConfiguration
refold's avatar
refold committed
692

693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
-- ------------------------------------------------------------
-- * Report flags
-- ------------------------------------------------------------

data ReportFlags = ReportFlags {
    reportUsername  :: Flag Username,
    reportPassword  :: Flag Password,
    reportVerbosity :: Flag Verbosity
  }

defaultReportFlags :: ReportFlags
defaultReportFlags = ReportFlags {
    reportUsername  = mempty,
    reportPassword  = mempty,
    reportVerbosity = toFlag normal
  }

reportCommand :: CommandUI ReportFlags
711
712
713
reportCommand = CommandUI {
    commandName         = "report",
    commandSynopsis     = "Upload build reports to a remote server.",
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
    commandDescription  = Just $ \_ ->
         "You can store your Hackage login in the ~/.cabal/config file\n",
    commandUsage        = \pname -> "Usage: " ++ pname ++ " report [FLAGS]\n\n"
      ++ "Flags for upload:",
    commandDefaultFlags = defaultReportFlags,
    commandOptions      = \_ ->
      [optionVerbosity reportVerbosity (\v flags -> flags { reportVerbosity = v })

      ,option ['u'] ["username"]
        "Hackage username."
        reportUsername (\v flags -> flags { reportUsername = v })
        (reqArg' "USERNAME" (toFlag . Username)
                            (flagToList . fmap unUsername))

      ,option ['p'] ["password"]
        "Hackage password."
        reportPassword (\v flags -> flags { reportPassword = v })
        (reqArg' "PASSWORD" (toFlag . Password)
                            (flagToList . fmap unPassword))
      ]
734
735
  }

736
737
738
739
740
741
742
743
744
745
746
747
748
instance Monoid ReportFlags where
  mempty = ReportFlags {
    reportUsername  = mempty,
    reportPassword  = mempty,
    reportVerbosity = mempty
  }
  mappend a b = ReportFlags {
    reportUsername  = combine reportUsername,
    reportPassword  = combine reportPassword,
    reportVerbosity = combine reportVerbosity
  }
    where combine field = field a `mappend` field b

749
-- ------------------------------------------------------------
750
-- * Get flags
751
752
-- ------------------------------------------------------------

753
754
755
756
757
758
data GetFlags = GetFlags {
    getDestDir          :: Flag FilePath,
    getPristine         :: Flag Bool,
    getSourceRepository :: Flag (Maybe RepoKind),
    getVerbosity        :: Flag Verbosity
  }
759

760
761
762
763
764
765
defaultGetFlags :: GetFlags
defaultGetFlags = GetFlags {
    getDestDir          = mempty,
    getPristine         = mempty,
    getSourceRepository = mempty,
    getVerbosity        = toFlag normal
766
767
   }

768
769
770
771
getCommand :: CommandUI GetFlags
getCommand = CommandUI {
    commandName         = "get",
    commandSynopsis     = "Gets a package's source code.",
772
773
774
775
776
    commandDescription  = Just $ \_ ->
          "Creates a local copy of a package's source code. By default it gets "
       ++ "the source\ntarball and unpacks it in a local subdirectory. "
       ++ "Alternatively, with -s it will\nget the code from the source "
       ++ "repository specified by the package.\n",
777
    commandUsage        = usagePackages "get",
778
    commandDefaultFlags = defaultGetFlags,
779
    commandOptions      = \_ -> [
780
        optionVerbosity getVerbosity (\v flags -> flags { getVerbosity = v })
781
782

       ,option "d" ["destdir"]
refold's avatar
refold committed
783
         "Where to place the package source, defaults to the current directory."
784
         getDestDir (\v flags -> flags { getDestDir = v })
785
         (reqArgFlag "PATH")
786

787
       ,option "s" ["source-repository"]
788
         "Copy the package's source repository (ie git clone, darcs get, etc as appropriate)."
789
790
791
792
793
794
         getSourceRepository (\v flags -> flags { getSourceRepository = v })
        (optArg "[head|this|...]" (readP_to_E (const "invalid source-repository")
                                              (fmap (toFlag . Just) parse))
                                  (Flag Nothing)
                                  (map (fmap show) . flagToList))

795
796
797
       , option [] ["pristine"]
           ("Unpack the original pristine tarball, rather than updating the "
           ++ ".cabal file with the latest revision from the package archive.")
798
           getPristine (\v flags -> flags { getPristine = v })
799
           trueArg
800
801
802
       ]
  }

803
804
805
806
807
808
809
-- 'cabal unpack' is a deprecated alias for 'cabal get'.
unpackCommand :: CommandUI GetFlags
unpackCommand = getCommand {
  commandName  = "unpack",
  commandUsage = usagePackages "unpack"
  }

810
instance Monoid GetFlags where
811
812
813
814
815
816
  mempty = GetFlags {
    getDestDir          = mempty,
    getPristine         = mempty,
    getSourceRepository = mempty,
    getVerbosity        = mempty
    }
817
818
819
820
821
  mappend a b = GetFlags {
    getDestDir          = combine getDestDir,
    getPristine         = combine getPristine,
    getSourceRepository = combine getSourceRepository,
    getVerbosity        = combine getVerbosity
822
823
824
  }
    where combine field = field a `mappend` field b

825
826
827
828
829
-- ------------------------------------------------------------
-- * List flags
-- ------------------------------------------------------------

data ListFlags = ListFlags {
830
    listInstalled    :: Flag Bool,
831
    listSimpleOutput :: Flag Bool,
832
833
    listVerbosity    :: Flag Verbosity,
    listPackageDBs   :: [Maybe PackageDB]
834
835
836
837
  }

defaultListFlags :: ListFlags
defaultListFlags = ListFlags {
838
    listInstalled    = Flag False,
839
    listSimpleOutput = Flag False,
840
841
    listVerbosity    = toFlag normal,
    listPackageDBs   = []
842
843
844
845
846
  }

listCommand  :: CommandUI ListFlags
listCommand = CommandUI {
    commandName         = "list",
847
    commandSynopsis     = "List packages matching a search string.",
848
    commandDescription  = Nothing,
refold's avatar
refold committed
849
    commandUsage        = usageFlagsOrPackages "list",
850
    commandDefaultFlags = defaultListFlags,
851
    commandOptions      = \_ -> [
852
        optionVerbosity listVerbosity (\v flags -> flags { listVerbosity = v })
853

854
        , option [] ["installed"]
855
856
857
858
            "Only print installed packages"
            listInstalled (\v flags -> flags { listInstalled = v })
            trueArg

859
860
861
862
863
        , option [] ["simple-output"]
            "Print in a easy-to-parse format"
            listSimpleOutput (\v flags -> flags { listSimpleOutput = v })
            trueArg

864
865
866
867
868
        , option "" ["package-db"]
          "Use a given package database. May be a specific file, 'global', 'user' or 'clear'."
          listPackageDBs (\v flags -> flags { listPackageDBs = v })
          (reqArg' "DB" readPackageDbList showPackageDbList)

869
870
871
872
        ]
  }

instance Monoid ListFlags where
873
874
875
876
877
878
  mempty = ListFlags {
    listInstalled    = mempty,
    listSimpleOutput = mempty,
    listVerbosity    = mempty,
    listPackageDBs   = mempty
    }
879
  mappend a b = ListFlags {
880
    listInstalled    = combine listInstalled,
881
    listSimpleOutput = combine listSimpleOutput,
882
883
    listVerbosity    = combine listVerbosity,
    listPackageDBs   = combine listPackageDBs
884
885
886
  }
    where combine field = field a `mappend` field b

887
888
889
890
891
-- ------------------------------------------------------------
-- * Info flags
-- ------------------------------------------------------------

data InfoFlags = InfoFlags {
892
893
    infoVerbosity  :: Flag Verbosity,
    infoPackageDBs :: [Maybe PackageDB]
894
895
896
897
  }

defaultInfoFlags :: InfoFlags
defaultInfoFlags = InfoFlags {
898
899
    infoVerbosity  = toFlag normal,
    infoPackageDBs = []
900
901
902
903
904
905
906
  }

infoCommand  :: CommandUI InfoFlags
infoCommand = CommandUI {
    commandName         = "info",
    commandSynopsis     = "Display detailed information about a particular package.",
    commandDescription  = Nothing,
refold's avatar
refold committed
907
    commandUsage        = usagePackages "info",
908
909
910
    commandDefaultFlags = defaultInfoFlags,
    commandOptions      = \_ -> [
        optionVerbosity infoVerbosity (\v flags -> flags { infoVerbosity = v })
911
912
913
914
915
916

        , option "" ["package-db"]
          "Use a given package database. May be a specific file, 'global', 'user' or 'clear'."
          infoPackageDBs (\v flags -> flags { infoPackageDBs = v })
          (reqArg' "DB" readPackageDbList showPackageDbList)

917
918
919
920
        ]
  }

instance Monoid InfoFlags where
921
922
923
924
  mempty = InfoFlags {
    infoVerbosity  = mempty,
    infoPackageDBs = mempty
    }
925
  mappend a b = InfoFlags {
926
927
    infoVerbosity  = combine infoVerbosity,
    infoPackageDBs = combine infoPackageDBs
928
929
930
  }
    where combine field = field a `mappend` field b

931
932
933
934
-- ------------------------------------------------------------
-- * Install flags
-- ------------------------------------------------------------

935
936
-- | Install takes the same flags as configure along with a few extras.
--
937
data InstallFlags = InstallFlags {
938
939
940
    installDocumentation    :: Flag Bool,
    installHaddockIndex     :: Flag PathTemplate,
    installDryRun           :: Flag Bool,
941
942
943
    installMaxBackjumps     :: Flag Int,
    installReorderGoals     :: Flag Bool,
    installIndependentGoals :: Flag Bool,
944
    installShadowPkgs       :: Flag Bool,
Andres Löh's avatar
Andres Löh committed
945
    installStrongFlags      :: Flag Bool,
946
947
    installReinstall        :: Flag Bool,
    installAvoidReinstalls  :: Flag Bool,
948
    installOverrideReinstall :: Flag Bool,
949
950
951
952
953
954
955
956
    installUpgradeDeps      :: Flag Bool,
    installOnly             :: Flag Bool,
    installOnlyDeps         :: Flag Bool,
    installRootCmd          :: Flag String,
    installSummaryFile      :: [PathTemplate],
    installLogFile          :: Flag PathTemplate,
    installBuildReports     :: Flag ReportLevel,
    installSymlinkBinDir    :: Flag FilePath,
957
    installOneShot          :: Flag Bool,
958
959
    installNumJobs          :: Flag (Maybe Int),
    installRunTests         :: Flag Bool
960
961
962
963
  }

defaultInstallFlags :: InstallFlags
defaultInstallFlags = InstallFlags {
964
965
966
    installDocumentation   = Flag False,
    installHaddockIndex    = Flag docIndexFile,
    installDryRun          = Flag False,
967
    installMaxBackjumps    = Flag defaultMaxBackjumps,
968
    installReorderGoals    = Flag False,
969
    installIndependentGoals= Flag False,
970
    installShadowPkgs      = Flag False,
Andres Löh's avatar
Andres Löh committed
971
    installStrongFlags     = Flag False,
972
973
    installReinstall       = Flag False,
    installAvoidReinstalls = Flag False,
974
    installOverrideReinstall = Flag False,
975
976
977
978
979
980
981
982
    installUpgradeDeps     = Flag False,
    installOnly            = Flag False,
    installOnlyDeps        = Flag False,
    installRootCmd         = mempty,
    installSummaryFile     = mempty,
    installLogFile         = mempty,
    installBuildReports    = Flag NoReports,
    installSymlinkBinDir   = mempty,
983
    installOneShot         = Flag False,
984
985
    installNumJobs         = mempty,
    installRunTests        = mempty
986
  }
987
988
  where
    docIndexFile = toPathTemplate ("$datadir" </> "doc" </> "index.html")
989

990
991
992
993
994
995
996
997
998
999
1000
allowNewerParser :: ReadE AllowNewer
allowNewerParser = ReadE $ \s ->
  case s of
    ""      -> Right AllowNewerNone
    "False" -> Right AllowNewerNone
    "True"  -> Right AllowNewerAll
    _       ->
      case readPToMaybe pkgsParser s of
        Just pkgs -> Right . AllowNewerSome $ pkgs
        Nothing   -> Left ("Cannot parse the list of packages: " ++ s)
  where