Setup.hs 64.9 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(..)
Duncan Coutts's avatar
Duncan Coutts committed
37
38

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

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

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

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

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

-- | Flags that apply at the top level, not to any sub-command.
data GlobalFlags = GlobalFlags {
108
109
110
111
112
113
114
115
    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,
116
    globalWorldFile         :: Flag FilePath,
117
118
    globalRequireSandbox    :: Flag Bool,
    globalIgnoreSandbox     :: Flag Bool
119
  }
Duncan Coutts's avatar
Duncan Coutts committed
120

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

globalCommand :: CommandUI GlobalFlags
globalCommand = CommandUI {
    commandName         = "",
    commandSynopsis     = "",
140
141
142
143
    commandUsage        = \_ ->
         "This program is the command line interface "
           ++ "to the Haskell Cabal infrastructure.\n"
      ++ "See http://www.haskell.org/cabal/ for more information.\n",
144
    commandDescription  = Just $ \pname ->
145
146
147
148
149
150
         "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",
151
    commandDefaultFlags = mempty,
152
    commandOptions      = \showOrParseArgs ->
153
      (case showOrParseArgs of ShowArgs -> take 6; ParseArgs -> id)
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
      [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")

169
170
171
172
173
174
      ,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")

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

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

185
186
187
188
189
190
191
192
193
194
195
196
197
198
      ,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)
199

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

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

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

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

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

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

279
280
281
282
283
    -- 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 }
284
    -- Cabal < 1.18.0 doesn't know about --extra-prog-path and --sysconfdir.
285
    flags_1_18_0 = flags_1_19_0 { configProgramPathExtra = []
286
287
                                , configInstallDirs = configInstallDirs_1_18_0}
    configInstallDirs_1_18_0 = (configInstallDirs flags) { sysconfdir = NoFlag }
288
    -- Cabal < 1.14.0 doesn't know about '--disable-benchmarks'.
289
    flags_1_14_0 = flags_1_18_0 { configBenchmarks  = NoFlag }
290
    -- Cabal < 1.10.0 doesn't know about '--disable-tests'.
291
    flags_1_10_0 = flags_1_14_0 { configTests       = NoFlag }
292
    -- Cabal < 1.3.10 does not grok the '--constraints' flag.
293
    flags_1_3_10 = flags_1_10_0 { configConstraints = [] }
294

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

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

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

configureExCommand :: CommandUI (ConfigFlags, ConfigExFlags)
configureExCommand = configureCommand {
    commandDefaultFlags = (mempty, defaultConfigExFlags),
    commandOptions      = \showOrParseArgs ->
317
         liftOptions fst setFst
318
         (filter ((`notElem` ["constraint", "dependency", "exact-configuration"])
319
                  . optionName) $ configureOptions  showOrParseArgs)
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
      ++ 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))
335
336
337
338
339
340
  , 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))
341
342
343
344

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

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

  , 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)

359
360
361
362
363
  ]

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

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

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

data BuildExFlags = BuildExFlags {
  buildOnly     :: Flag SkipAddSourceDepsCheck
}

buildExOptions :: ShowOrParseArgs -> [OptionField BuildExFlags]
buildExOptions _showOrParseArgs =
392
  option [] ["only"]
393
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
  "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
-- ------------------------------------------------------------

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

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

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

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

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

473
-- ------------------------------------------------------------
474
-- * Fetch command
475
-- ------------------------------------------------------------
476

477
478
479
480
data FetchFlags = FetchFlags {
--    fetchOutput    :: Flag FilePath,
      fetchDeps      :: Flag Bool,
      fetchDryRun    :: Flag Bool,
481
      fetchSolver           :: Flag PreSolver,
482
483
484
      fetchMaxBackjumps     :: Flag Int,
      fetchReorderGoals     :: Flag Bool,
      fetchIndependentGoals :: Flag Bool,
485
      fetchShadowPkgs       :: Flag Bool,
486
487
488
489
490
491
492
493
      fetchVerbosity :: Flag Verbosity
    }

defaultFetchFlags :: FetchFlags
defaultFetchFlags = FetchFlags {
--  fetchOutput    = mempty,
    fetchDeps      = toFlag True,
    fetchDryRun    = toFlag False,
494
495
496
497
    fetchSolver           = Flag defaultSolver,
    fetchMaxBackjumps     = Flag defaultMaxBackjumps,
    fetchReorderGoals     = Flag False,
    fetchIndependentGoals = Flag False,
498
    fetchShadowPkgs       = Flag False,
499
500
501
502
    fetchVerbosity = toFlag normal
   }

fetchCommand :: CommandUI FetchFlags
Duncan Coutts's avatar
Duncan Coutts committed
503
504
fetchCommand = CommandUI {
    commandName         = "fetch",
505
    commandSynopsis     = "Downloads packages for later installation.",
Duncan Coutts's avatar
Duncan Coutts committed
506
    commandDescription  = Nothing,
refold's avatar
refold committed
507
    commandUsage        = usagePackages "fetch",
508
    commandDefaultFlags = defaultFetchFlags,
509
    commandOptions      = \ showOrParseArgs -> [
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
         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
531
532
533
534

       ] ++

       optionSolver      fetchSolver           (\v flags -> flags { fetchSolver           = v }) :
535
536
       optionSolverFlags showOrParseArgs
                         fetchMaxBackjumps     (\v flags -> flags { fetchMaxBackjumps     = v })
537
538
                         fetchReorderGoals     (\v flags -> flags { fetchReorderGoals     = v })
                         fetchIndependentGoals (\v flags -> flags { fetchIndependentGoals = v })
539
                         fetchShadowPkgs       (\v flags -> flags { fetchShadowPkgs       = v })
540

Duncan Coutts's avatar
Duncan Coutts committed
541
542
  }

543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
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
-- ------------------------------------------------------------
-- * Freeze command
-- ------------------------------------------------------------

data FreezeFlags = FreezeFlags {
      freezeDryRun           :: Flag Bool,
      freezeSolver           :: Flag PreSolver,
      freezeMaxBackjumps     :: Flag Int,
      freezeReorderGoals     :: Flag Bool,
      freezeIndependentGoals :: Flag Bool,
      freezeShadowPkgs       :: Flag Bool,
      freezeVerbosity        :: Flag Verbosity
    }

defaultFreezeFlags :: FreezeFlags
defaultFreezeFlags = FreezeFlags {
    freezeDryRun           = toFlag False,
    freezeSolver           = Flag defaultSolver,
    freezeMaxBackjumps     = Flag defaultMaxBackjumps,
    freezeReorderGoals     = Flag False,
    freezeIndependentGoals = Flag False,
    freezeShadowPkgs       = Flag False,
    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

       ] ++

       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 })

  }

594
595
596
597
-- ------------------------------------------------------------
-- * Other commands
-- ------------------------------------------------------------

598
updateCommand  :: CommandUI (Flag Verbosity)
Duncan Coutts's avatar
Duncan Coutts committed
599
600
updateCommand = CommandUI {
    commandName         = "update",
601
    commandSynopsis     = "Updates list of known packages.",
Duncan Coutts's avatar
Duncan Coutts committed
602
    commandDescription  = Nothing,
refold's avatar
refold committed
603
    commandUsage        = usageFlags "update",
604
    commandDefaultFlags = toFlag normal,
605
    commandOptions      = \_ -> [optionVerbosity id const]
Duncan Coutts's avatar
Duncan Coutts committed
606
607
  }

608
upgradeCommand  :: CommandUI (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags)
609
upgradeCommand = configureCommand {
ijones's avatar
ijones committed
610
    commandName         = "upgrade",
611
    commandSynopsis     = "(command disabled, use install instead)",
ijones's avatar
ijones committed
612
    commandDescription  = Nothing,
refold's avatar
refold committed
613
    commandUsage        = usageFlagsOrPackages "upgrade",
614
    commandDefaultFlags = (mempty, mempty, mempty, mempty),
615
    commandOptions      = commandOptions installCommand
ijones's avatar
ijones committed
616
617
  }

Duncan Coutts's avatar
Duncan Coutts committed
618
619
620
621
622
623
624
625
626
627
628
{-
cleanCommand  :: CommandUI ()
cleanCommand = makeCommand name shortDesc longDesc emptyFlags options
  where
    name       = "clean"
    shortDesc  = "Removes downloaded files"
    longDesc   = Nothing
    emptyFlags = ()
    options _  = []
-}

629
630
631
checkCommand  :: CommandUI (Flag Verbosity)
checkCommand = CommandUI {
    commandName         = "check",
632
    commandSynopsis     = "Check the package for common mistakes.",
633
634
    commandDescription  = Nothing,
    commandUsage        = \pname -> "Usage: " ++ pname ++ " check\n",
635
    commandDefaultFlags = toFlag normal,
636
    commandOptions      = \_ -> []
637
638
  }

639
640
641
642
643
644
645
646
647
648
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      = \_ -> []
  }

649
runCommand :: CommandUI (BuildFlags, BuildExFlags)
refold's avatar
refold committed
650
651
652
653
654
runCommand = CommandUI {
    commandName         = "run",
    commandSynopsis     = "Runs the compiled executable.",
    commandDescription  = Nothing,
    commandUsage        =
655
656
657
      \pname -> "Usage: " ++ pname
                ++ " run [FLAGS] [EXECUTABLE] [-- EXECUTABLE_FLAGS]\n\n"
                ++ "Flags for run:",
refold's avatar
refold committed
658
    commandDefaultFlags = mempty,
659
660
    commandOptions      =
      \showOrParseArgs -> liftOptions fst setFst
661
                          (commandOptions parent showOrParseArgs)
662
663
664
                          ++
                          liftOptions snd setSnd
                          (buildExOptions showOrParseArgs)
refold's avatar
refold committed
665
666
  }
  where
667
668
669
    setFst a (_,b) = (a,b)
    setSnd b (a,_) = (a,b)

670
    parent = Cabal.buildCommand defaultProgramConfiguration
refold's avatar
refold committed
671

672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
-- ------------------------------------------------------------
-- * 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
690
691
692
reportCommand = CommandUI {
    commandName         = "report",
    commandSynopsis     = "Upload build reports to a remote server.",
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
    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))
      ]
713
714
  }

715
716
717
718
719
720
721
722
723
724
725
726
727
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

728
-- ------------------------------------------------------------
729
-- * Get flags
730
731
-- ------------------------------------------------------------

732
733
734
735
736
737
data GetFlags = GetFlags {
    getDestDir          :: Flag FilePath,
    getPristine         :: Flag Bool,
    getSourceRepository :: Flag (Maybe RepoKind),
    getVerbosity        :: Flag Verbosity
  }
738

739
740
741
742
743
744
defaultGetFlags :: GetFlags
defaultGetFlags = GetFlags {
    getDestDir          = mempty,
    getPristine         = mempty,
    getSourceRepository = mempty,
    getVerbosity        = toFlag normal
745
746
   }

747
748
749
750
getCommand :: CommandUI GetFlags
getCommand = CommandUI {
    commandName         = "get",
    commandSynopsis     = "Gets a package's source code.",
751
752
753
754
755
    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",
756
    commandUsage        = usagePackages "get",
757
    commandDefaultFlags = defaultGetFlags,
758
    commandOptions      = \_ -> [
759
        optionVerbosity getVerbosity (\v flags -> flags { getVerbosity = v })
760
761

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

766
       ,option "s" ["source-repository"]
767
         "Copy the package's source repository (ie git clone, darcs get, etc as appropriate)."
768
769
770
771
772
773
         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))

774
775
776
       , option [] ["pristine"]
           ("Unpack the original pristine tarball, rather than updating the "
           ++ ".cabal file with the latest revision from the package archive.")
777
           getPristine (\v flags -> flags { getPristine = v })
778
           trueArg
779
780
781
       ]
  }

782
783
784
785
786
787
788
-- 'cabal unpack' is a deprecated alias for 'cabal get'.
unpackCommand :: CommandUI GetFlags
unpackCommand = getCommand {
  commandName  = "unpack",
  commandUsage = usagePackages "unpack"
  }

789
instance Monoid GetFlags where
790
791
792
793
794
795
  mempty = GetFlags {
    getDestDir          = mempty,
    getPristine         = mempty,
    getSourceRepository = mempty,
    getVerbosity        = mempty
    }
796
797
798
799
800
  mappend a b = GetFlags {
    getDestDir          = combine getDestDir,
    getPristine         = combine getPristine,
    getSourceRepository = combine getSourceRepository,
    getVerbosity        = combine getVerbosity
801
802
803
  }
    where combine field = field a `mappend` field b

804
805
806
807
808
-- ------------------------------------------------------------
-- * List flags
-- ------------------------------------------------------------

data ListFlags = ListFlags {
809
    listInstalled    :: Flag Bool,
810
    listSimpleOutput :: Flag Bool,
811
812
    listVerbosity    :: Flag Verbosity,
    listPackageDBs   :: [Maybe PackageDB]
813
814
815
816
  }

defaultListFlags :: ListFlags
defaultListFlags = ListFlags {
817
    listInstalled    = Flag False,
818
    listSimpleOutput = Flag False,
819
820
    listVerbosity    = toFlag normal,
    listPackageDBs   = []
821
822
823
824
825
  }

listCommand  :: CommandUI ListFlags
listCommand = CommandUI {
    commandName         = "list",
826
    commandSynopsis     = "List packages matching a search string.",
827
    commandDescription  = Nothing,
refold's avatar
refold committed
828
    commandUsage        = usageFlagsOrPackages "list",
829
    commandDefaultFlags = defaultListFlags,
830
    commandOptions      = \_ -> [
831
        optionVerbosity listVerbosity (\v flags -> flags { listVerbosity = v })
832

833
        , option [] ["installed"]
834
835
836
837
            "Only print installed packages"
            listInstalled (\v flags -> flags { listInstalled = v })
            trueArg

838
839
840
841
842
        , option [] ["simple-output"]
            "Print in a easy-to-parse format"
            listSimpleOutput (\v flags -> flags { listSimpleOutput = v })
            trueArg

843
844
845
846
847
        , 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)

848
849
850
851
        ]
  }

instance Monoid ListFlags where
852
853
854
855
856
857
  mempty = ListFlags {
    listInstalled    = mempty,
    listSimpleOutput = mempty,
    listVerbosity    = mempty,
    listPackageDBs   = mempty
    }
858
  mappend a b = ListFlags {
859
    listInstalled    = combine listInstalled,
860
    listSimpleOutput = combine listSimpleOutput,
861
862
    listVerbosity    = combine listVerbosity,
    listPackageDBs   = combine listPackageDBs
863
864
865
  }
    where combine field = field a `mappend` field b

866
867
868
869
870
-- ------------------------------------------------------------
-- * Info flags
-- ------------------------------------------------------------

data InfoFlags = InfoFlags {
871
872
    infoVerbosity  :: Flag Verbosity,
    infoPackageDBs :: [Maybe PackageDB]
873
874
875
876
  }

defaultInfoFlags :: InfoFlags
defaultInfoFlags = InfoFlags {
877
878
    infoVerbosity  = toFlag normal,
    infoPackageDBs = []
879
880
881
882
883
884
885
  }

infoCommand  :: CommandUI InfoFlags
infoCommand = CommandUI {
    commandName         = "info",
    commandSynopsis     = "Display detailed information about a particular package.",
    commandDescription  = Nothing,
refold's avatar
refold committed
886
    commandUsage        = usagePackages "info",
887
888
889
    commandDefaultFlags = defaultInfoFlags,
    commandOptions      = \_ -> [
        optionVerbosity infoVerbosity (\v flags -> flags { infoVerbosity = v })
890
891
892
893
894
895

        , 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)

896
897
898
899
        ]
  }

instance Monoid InfoFlags where
900
901
902
903
  mempty = InfoFlags {
    infoVerbosity  = mempty,
    infoPackageDBs = mempty
    }
904
  mappend a b = InfoFlags {
905
906
    infoVerbosity  = combine infoVerbosity,
    infoPackageDBs = combine infoPackageDBs
907
908
909
  }
    where combine field = field a `mappend` field b

910
911
912
913
-- ------------------------------------------------------------
-- * Install flags
-- ------------------------------------------------------------

914
915
-- | Install takes the same flags as configure along with a few extras.
--
916
data InstallFlags = InstallFlags {
917
918
919
    installDocumentation    :: Flag Bool,
    installHaddockIndex     :: Flag PathTemplate,
    installDryRun           :: Flag Bool,
920
921
922
    installMaxBackjumps     :: Flag Int,
    installReorderGoals     :: Flag Bool,
    installIndependentGoals :: Flag Bool,
923
    installShadowPkgs       :: Flag Bool,
924
925
    installReinstall        :: Flag Bool,
    installAvoidReinstalls  :: Flag Bool,
926
    installOverrideReinstall :: Flag Bool,
927
928
929
930
931
932
933
934
    installUpgradeDeps      :: Flag Bool,
    installOnly             :: Flag Bool,
    installOnlyDeps         :: Flag Bool,
    installRootCmd          :: Flag String,
    installSummaryFile      :: [PathTemplate],
    installLogFile          :: Flag PathTemplate,
    installBuildReports     :: Flag ReportLevel,
    installSymlinkBinDir    :: Flag FilePath,
935
    installOneShot          :: Flag Bool,
936
937
    installNumJobs          :: Flag (Maybe Int),
    installRunTests         :: Flag Bool
938
939
940
941
  }

defaultInstallFlags :: InstallFlags
defaultInstallFlags = InstallFlags {
942
943
944
    installDocumentation   = Flag False,
    installHaddockIndex    = Flag docIndexFile,
    installDryRun          = Flag False,
945
946
947
    installMaxBackjumps    = Flag defaultMaxBackjumps,
    installReorderGoals    = Flag False,
    installIndependentGoals= Flag False,
948
    installShadowPkgs      = Flag False,
949
950
    installReinstall       = Flag False,
    installAvoidReinstalls = Flag False,
951
    installOverrideReinstall = Flag False,
952
953
954
955
956
957
958
959
    installUpgradeDeps     = Flag False,
    installOnly            = Flag False,
    installOnlyDeps        = Flag False,
    installRootCmd         = mempty,
    installSummaryFile     = mempty,
    installLogFile         = mempty,
    installBuildReports    = Flag NoReports,
    installSymlinkBinDir   = mempty,
960
    installOneShot         = Flag False,
961
962
    installNumJobs         = mempty,
    installRunTests        = mempty
963
  }
964
965
  where
    docIndexFile = toPathTemplate ("$datadir" </> "doc" </> "index.html")
966

967
968
969
970
971
972
973
974
975
976
977
978
979
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
    pkgsParser = Parse.sepBy1 parse (Parse.char ',')

980
981
982
983
984
985
986
987
allowNewerPrinter :: Flag AllowNewer -> [Maybe String]
allowNewerPrinter (Flag AllowNewerNone)        = [Just "False"]
allowNewerPrinter (Flag AllowNewerAll)         = [Just "True"]
allowNewerPrinter (Flag (AllowNewerSome pkgs)) =
  [Just . intercalate "," . map display $ pkgs]
allowNewerPrinter NoFlag                       = []


988
989
990
defaultMaxBackjumps :: Int
defaultMaxBackjumps = 200

991
992
defaultSolver :: PreSolver
defaultSolver = Choose
993
994

allSolvers :: String
995
allSolvers = intercalate ", " (map display ([minBound .. maxBound] :: [PreSolver]))
996

997
installCommand :: CommandUI (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags)
998
installCommand = CommandUI {
999
1000
  commandName         = "install",
  commandSynopsis     = "Installs a list of packages.",