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

    , parsePackageArgs
42
43
44
    --TODO: stop exporting these:
    , showRepo
    , parseRepo
45
46
    ) where

47
import Distribution.Client.Types
48
         ( Username(..), Password(..), Repo(..), RemoteRepo(..), LocalRepo(..) )
49
50
import Distribution.Client.BuildReports.Types
         ( ReportLevel(..) )
51
import Distribution.Client.Dependency.Types
52
         ( AllowNewer(..), PreSolver(..) )
53
54
import qualified Distribution.Client.Init.Types as IT
         ( InitFlags(..), PackageType(..) )
55
56
import Distribution.Client.Targets
         ( UserConstraint, readUserConstraint )
57
58
import Distribution.Utils.NubList
         ( NubList, toNubList, fromNubList)
59

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

93
94
import Data.Char
         ( isSpace, isAlphaNum )
95
import Data.List
96
         ( intercalate, deleteFirstsBy )
97
import Data.Maybe
98
         ( listToMaybe, maybeToList, fromMaybe )
99
#if !MIN_VERSION_base(4,8,0)
100
101
import Data.Monoid
         ( Monoid(..) )
102
#endif
103
104
105
106
107
108
import Control.Monad
         ( liftM )
import System.FilePath
         ( (</>) )
import Network.URI
         ( parseAbsoluteURI, uriToString )
109

110
111
112
113
114
115
-- ------------------------------------------------------------
-- * Global flags
-- ------------------------------------------------------------

-- | Flags that apply at the top level, not to any sub-command.
data GlobalFlags = GlobalFlags {
116
117
118
119
    globalVersion           :: Flag Bool,
    globalNumericVersion    :: Flag Bool,
    globalConfigFile        :: Flag FilePath,
    globalSandboxConfigFile :: Flag FilePath,
120
    globalRemoteRepos       :: NubList RemoteRepo,     -- ^ Available Hackage servers.
121
    globalCacheDir          :: Flag FilePath,
122
    globalLocalRepos        :: NubList FilePath,
123
    globalLogsDir           :: Flag FilePath,
124
    globalWorldFile         :: Flag FilePath,
125
126
    globalRequireSandbox    :: Flag Bool,
    globalIgnoreSandbox     :: Flag Bool
127
  }
Duncan Coutts's avatar
Duncan Coutts committed
128

129
130
defaultGlobalFlags :: GlobalFlags
defaultGlobalFlags  = GlobalFlags {
131
132
133
134
    globalVersion           = Flag False,
    globalNumericVersion    = Flag False,
    globalConfigFile        = mempty,
    globalSandboxConfigFile = mempty,
135
    globalRemoteRepos       = mempty,
136
137
138
    globalCacheDir          = mempty,
    globalLocalRepos        = mempty,
    globalLogsDir           = mempty,
139
    globalWorldFile         = mempty,
140
141
    globalRequireSandbox    = Flag False,
    globalIgnoreSandbox     = Flag False
142
143
  }

144
145
globalCommand :: [Command action] -> CommandUI GlobalFlags
globalCommand commands = CommandUI {
146
    commandName         = "",
147
148
    commandSynopsis     =
         "Command line interface to the Haskell Cabal infrastructure.",
149
150
151
152
    commandUsage        = \pname ->
         "See http://www.haskell.org/cabal/ for more information.\n"
      ++ "\n"
      ++ "Usage: " ++ pname ++ " [GLOBAL FLAGS] [COMMAND [FLAGS]]\n",
153
    commandDescription  = Just $ \pname ->
154
155
156
      let
        commands' = commands ++ [commandAddAction helpCommandUI undefined]
        cmdDescs = getNormalCommandDescriptions commands'
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
        -- if new commands are added, we want them to appear even if they
        -- are not included in the custom listing below. Thus, we calculate
        -- the `otherCmds` list and append it under the `other` category.
        -- Alternatively, a new testcase could be added that ensures that
        -- the set of commands listed here is equal to the set of commands
        -- that are actually available.
        otherCmds = deleteFirstsBy (==) (map fst cmdDescs)
          [ "help"
          , "update"
          , "install"
          , "fetch"
          , "list"
          , "info"
          , "user-config"
          , "get"
          , "init"
          , "configure"
          , "build"
          , "clean"
          , "run"
          , "repl"
          , "test"
          , "bench"
          , "check"
          , "sdist"
          , "upload"
          , "report"
          , "freeze"
          , "haddock"
          , "hscolour"
          , "copy"
          , "register"
          , "sandbox"
          , "exec"
          ]
192
193
        maxlen    = maximum $ [length name | (name, _) <- cmdDescs]
        align str = str ++ replicate (maxlen - length str) ' '
194
195
196
197
198
199
200
201
202
        startGroup n = " ["++n++"]"
        par          = ""
        addCmd n     = case lookup n cmdDescs of
                         Nothing -> ""
                         Just d -> "  " ++ align n ++ "    " ++ d
        addCmdCustom n d = case lookup n cmdDescs of -- make sure that the
                                                  -- command still exists.
                         Nothing -> ""
                         Just _ -> "  " ++ align n ++ "    " ++ d
203
204
      in
         "Commands:\n"
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
      ++ unlines (
        [ startGroup "global"
        , addCmd "update"
        , addCmd "install"
        , par
        , addCmd "help"
        , addCmd "info"
        , addCmd "list"
        , addCmd "fetch"
        , addCmd "user-config"
        , par
        , startGroup "package"
        , addCmd "get"
        , addCmd "init"
        , par
        , addCmd "configure"
        , addCmd "build"
        , addCmd "clean"
        , par
        , addCmd "run"
        , addCmd "repl"
        , addCmd "test"
        , addCmd "bench"
        , par
        , addCmd "check"
        , addCmd "sdist"
        , addCmd "upload"
        , addCmd "report"
        , par
        , addCmd "freeze"
        , addCmd "haddock"
        , addCmd "hscolour"
        , addCmd "copy"
        , addCmd "register"
        , par
        , startGroup "sandbox"
241
        , addCmd "sandbox"
242
243
244
245
246
        , addCmd "exec"
        , addCmdCustom "repl" "Open interpreter with access to sandbox packages."
        ] ++ if null otherCmds then [] else par
                                           :startGroup "other"
                                           :[addCmd n | n <- otherCmds])
247
248
      ++ "\n"
      ++ "For more information about a command use:\n"
249
250
      ++ "   " ++ pname ++ " COMMAND --help\n"
      ++ "or " ++ pname ++ " help COMMAND\n"
251
      ++ "\n"
252
      ++ "To install Cabal packages from hackage use:\n"
253
254
      ++ "  " ++ pname ++ " install foo [--dry-run]\n"
      ++ "\n"
255
256
      ++ "Occasionally you need to update the list of available packages:\n"
      ++ "  " ++ pname ++ " update\n",
257
    commandNotes = Nothing,
258
    commandDefaultFlags = mempty,
259
    commandOptions      = \showOrParseArgs ->
260
      (case showOrParseArgs of ShowArgs -> take 6; ParseArgs -> id)
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
      [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")

276
      ,option [] ["sandbox-config-file"]
277
         "Set an alternate location for the sandbox config file (default: './cabal.sandbox.config')"
278
279
280
         globalConfigFile (\v flags -> flags { globalSandboxConfigFile = v })
         (reqArgFlag "FILE")

281
      ,option [] ["require-sandbox"]
Mikhail Glushenkov's avatar
Mikhail Glushenkov committed
282
         "requiring the presence of a sandbox for sandbox-aware commands"
283
284
285
         globalRequireSandbox (\v flags -> flags { globalRequireSandbox = v })
         (boolOpt' ([], ["require-sandbox"]) ([], ["no-require-sandbox"]))

286
287
288
289
290
      ,option [] ["ignore-sandbox"]
         "Ignore any existing sandbox"
         globalIgnoreSandbox (\v flags -> flags { globalIgnoreSandbox = v })
         trueArg

291
292
293
      ,option [] ["remote-repo"]
         "The name and url for a remote repository"
         globalRemoteRepos (\v flags -> flags { globalRemoteRepos = v })
294
         (reqArg' "NAME:URL" (toNubList . maybeToList . readRepo) (map showRepo . fromNubList))
295
296
297
298
299
300
301
302
303

      ,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 })
304
         (reqArg' "DIR" (\x -> toNubList [x]) fromNubList)
305

306
307
308
309
310
      ,option [] ["logs-dir"]
         "The location to put log files"
         globalLogsDir (\v flags -> flags { globalLogsDir = v })
         (reqArgFlag "DIR")

311
312
313
314
      ,option [] ["world-file"]
         "The location of the world file"
         globalWorldFile (\v flags -> flags { globalWorldFile = v })
         (reqArgFlag "FILE")
315
316
317
318
319
      ]
  }

instance Monoid GlobalFlags where
  mempty = GlobalFlags {
320
321
322
323
324
325
326
327
    globalVersion           = mempty,
    globalNumericVersion    = mempty,
    globalConfigFile        = mempty,
    globalSandboxConfigFile = mempty,
    globalRemoteRepos       = mempty,
    globalCacheDir          = mempty,
    globalLocalRepos        = mempty,
    globalLogsDir           = mempty,
328
    globalWorldFile         = mempty,
329
330
    globalRequireSandbox    = mempty,
    globalIgnoreSandbox     = mempty
331
332
  }
  mappend a b = GlobalFlags {
333
334
335
336
337
338
339
340
    globalVersion           = combine globalVersion,
    globalNumericVersion    = combine globalNumericVersion,
    globalConfigFile        = combine globalConfigFile,
    globalSandboxConfigFile = combine globalConfigFile,
    globalRemoteRepos       = combine globalRemoteRepos,
    globalCacheDir          = combine globalCacheDir,
    globalLocalRepos        = combine globalLocalRepos,
    globalLogsDir           = combine globalLogsDir,
341
    globalWorldFile         = combine globalWorldFile,
342
343
    globalRequireSandbox    = combine globalRequireSandbox,
    globalIgnoreSandbox     = combine globalIgnoreSandbox
Duncan Coutts's avatar
Duncan Coutts committed
344
  }
345
346
347
348
349
350
351
    where combine field = field a `mappend` field b

globalRepos :: GlobalFlags -> [Repo]
globalRepos globalFlags = remoteRepos ++ localRepos
  where
    remoteRepos =
      [ Repo (Left remote) cacheDir
352
      | remote <- fromNubList $ globalRemoteRepos globalFlags
353
354
355
356
      , let cacheDir = fromFlag (globalCacheDir globalFlags)
                   </> remoteRepoName remote ]
    localRepos =
      [ Repo (Right LocalRepo) local
357
      | local <- fromNubList $ globalLocalRepos globalFlags ]
358
359
360
361

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

363
configureCommand :: CommandUI ConfigFlags
364
configureCommand = (Cabal.configureCommand defaultProgramConfiguration) {
365
    commandDefaultFlags = mempty
Duncan Coutts's avatar
Duncan Coutts committed
366
367
  }

368
369
370
configureOptions ::  ShowOrParseArgs -> [OptionField ConfigFlags]
configureOptions = commandOptions configureCommand

371
filterConfigureFlags :: ConfigFlags -> Version -> ConfigFlags
372
filterConfigureFlags flags cabalLibVersion
373
374
  | cabalLibVersion >= Version [1,21,1] [] = flags_latest
  -- ^ NB: we expect the latest version to be the most common case.
375
376
377
  | 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
378
  | cabalLibVersion <  Version [1,18,0] [] = flags_1_18_0
379
  | cabalLibVersion <  Version [1,19,1] [] = flags_1_19_0
380
  | cabalLibVersion <  Version [1,19,2] [] = flags_1_19_1
381
  | cabalLibVersion <  Version [1,21,1] [] = flags_1_20_0
382
  | otherwise = flags_latest
383
  where
384
    -- Cabal >= 1.19.1 uses '--dependency' and does not need '--constraint'.
385
386
    flags_latest = flags        { configConstraints = [] }

387
    -- Cabal < 1.21.1 doesn't know about 'disable-relocatable'
388
389
390
391
392
393
394
    -- Cabal < 1.21.1 doesn't know about 'enable-profiling'
    flags_1_20_0 =
      flags_latest { configRelocatable = NoFlag
                   , configProf = NoFlag
                   , configProfExe = configProf flags
                   , configProfLib =
                     mappend (configProf flags) (configProfLib flags)
395
396
                   , configCoverage = NoFlag
                   , configLibCoverage = configCoverage flags
397
                   }
398
    -- Cabal < 1.19.2 doesn't know about '--exact-configuration'.
399
    flags_1_19_1 = flags_1_20_0 { configExactConfiguration = NoFlag }
400
401
402
    -- Cabal < 1.19.1 uses '--constraint' instead of '--dependency'.
    flags_1_19_0 = flags_1_19_1 { configDependencies = []
                                , configConstraints  = configConstraints flags }
403
    -- Cabal < 1.18.0 doesn't know about --extra-prog-path and --sysconfdir.
404
    flags_1_18_0 = flags_1_19_0 { configProgramPathExtra = toNubList []
405
406
                                , configInstallDirs = configInstallDirs_1_18_0}
    configInstallDirs_1_18_0 = (configInstallDirs flags) { sysconfdir = NoFlag }
407
    -- Cabal < 1.14.0 doesn't know about '--disable-benchmarks'.
408
    flags_1_14_0 = flags_1_18_0 { configBenchmarks  = NoFlag }
409
    -- Cabal < 1.10.0 doesn't know about '--disable-tests'.
410
    flags_1_10_0 = flags_1_14_0 { configTests       = NoFlag }
411
    -- Cabal < 1.3.10 does not grok the '--constraints' flag.
412
    flags_1_3_10 = flags_1_10_0 { configConstraints = [] }
413

414
415
416
417
418
419
420
421
-- ------------------------------------------------------------
-- * Config extra flags
-- ------------------------------------------------------------

-- | cabal configure takes some extra flags beyond runghc Setup configure
--
data ConfigExFlags = ConfigExFlags {
    configCabalVersion :: Flag Version,
422
    configExConstraints:: [UserConstraint],
423
    configPreferences  :: [Dependency],
424
425
    configSolver       :: Flag PreSolver,
    configAllowNewer   :: Flag AllowNewer
426
427
428
  }

defaultConfigExFlags :: ConfigExFlags
429
430
defaultConfigExFlags = mempty { configSolver     = Flag defaultSolver
                              , configAllowNewer = Flag AllowNewerNone }
431
432
433
434
435

configureExCommand :: CommandUI (ConfigFlags, ConfigExFlags)
configureExCommand = configureCommand {
    commandDefaultFlags = (mempty, defaultConfigExFlags),
    commandOptions      = \showOrParseArgs ->
436
         liftOptions fst setFst
437
         (filter ((`notElem` ["constraint", "dependency", "exact-configuration"])
438
                  . optionName) $ configureOptions  showOrParseArgs)
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
      ++ 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))
454
455
456
457
458
459
  , 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))
460
461
462
463

  , option [] ["preference"]
      "Specify preferences (soft constraints) on the version of a package"
      configPreferences (\v flags -> flags { configPreferences = v })
464
465
466
467
      (reqArg "CONSTRAINT"
              (readP_to_E (const "dependency expected")
                          (fmap (\x -> [x]) parse))
              (map display))
468
469

  , optionSolver configSolver (\v flags -> flags { configSolver = v })
470
471

  , option [] ["allow-newer"]
cheecheeo's avatar
cheecheeo committed
472
    ("Ignore upper bounds in all dependencies or " ++ allowNewerArgument)
473
    configAllowNewer (\v flags -> flags { configAllowNewer = v})
cheecheeo's avatar
cheecheeo committed
474
    (optArg allowNewerArgument
475
476
477
     (fmap Flag allowNewerParser) (Flag AllowNewerAll)
     allowNewerPrinter)

478
  ]
cheecheeo's avatar
cheecheeo committed
479
  where allowNewerArgument = "DEPS"
480
481
482
483

instance Monoid ConfigExFlags where
  mempty = ConfigExFlags {
    configCabalVersion = mempty,
484
    configExConstraints= mempty,
485
    configPreferences  = mempty,
486
487
    configSolver       = mempty,
    configAllowNewer   = mempty
488
489
490
  }
  mappend a b = ConfigExFlags {
    configCabalVersion = combine configCabalVersion,
491
    configExConstraints= combine configExConstraints,
492
    configPreferences  = combine configPreferences,
493
494
    configSolver       = combine configSolver,
    configAllowNewer   = combine configAllowNewer
495
496
497
  }
    where combine field = field a `mappend` field b

ttuegel's avatar
ttuegel committed
498
499
500
501
-- ------------------------------------------------------------
-- * Build flags
-- ------------------------------------------------------------

502
503
504
505
506
507
508
509
510
511
data SkipAddSourceDepsCheck =
  SkipAddSourceDepsCheck | DontSkipAddSourceDepsCheck
  deriving Eq

data BuildExFlags = BuildExFlags {
  buildOnly     :: Flag SkipAddSourceDepsCheck
}

buildExOptions :: ShowOrParseArgs -> [OptionField BuildExFlags]
buildExOptions _showOrParseArgs =
512
  option [] ["only"]
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
  "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

-- ------------------------------------------------------------
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
-- * Repl command
-- ------------------------------------------------------------

replCommand :: CommandUI (ReplFlags, BuildExFlags)
replCommand = 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.replCommand defaultProgramConfiguration

562
563
564
565
-- ------------------------------------------------------------
-- * Test command
-- ------------------------------------------------------------

566
testCommand :: CommandUI (TestFlags, BuildFlags, BuildExFlags)
567
testCommand = parent {
568
569
  commandDefaultFlags = (commandDefaultFlags parent,
                         Cabal.defaultBuildFlags, mempty),
570
  commandOptions      =
571
    \showOrParseArgs -> liftOptions get1 set1
572
573
                        (commandOptions parent showOrParseArgs)
                        ++
574
575
576
577
                        liftOptions get2 set2
                        (Cabal.buildOptions progConf showOrParseArgs)
                        ++
                        liftOptions get3 set3 (buildExOptions showOrParseArgs)
578
579
  }
  where
580
581
582
    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)
583

584
585
    parent   = Cabal.testCommand
    progConf = defaultProgramConfiguration
586
587
588
589
590

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

591
benchmarkCommand :: CommandUI (BenchmarkFlags, BuildFlags, BuildExFlags)
592
benchmarkCommand = parent {
593
594
  commandDefaultFlags = (commandDefaultFlags parent,
                         Cabal.defaultBuildFlags, mempty),
595
  commandOptions      =
596
    \showOrParseArgs -> liftOptions get1 set1
597
598
                        (commandOptions parent showOrParseArgs)
                        ++
599
600
601
602
                        liftOptions get2 set2
                        (Cabal.buildOptions progConf showOrParseArgs)
                        ++
                        liftOptions get3 set3 (buildExOptions showOrParseArgs)
ttuegel's avatar
ttuegel committed
603
  }
604
  where
605
606
607
    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)
608

609
610
    parent   = Cabal.benchmarkCommand
    progConf = defaultProgramConfiguration
ttuegel's avatar
ttuegel committed
611

612
-- ------------------------------------------------------------
613
-- * Fetch command
614
-- ------------------------------------------------------------
615

616
617
618
619
data FetchFlags = FetchFlags {
--    fetchOutput    :: Flag FilePath,
      fetchDeps      :: Flag Bool,
      fetchDryRun    :: Flag Bool,
620
      fetchSolver           :: Flag PreSolver,
621
622
623
      fetchMaxBackjumps     :: Flag Int,
      fetchReorderGoals     :: Flag Bool,
      fetchIndependentGoals :: Flag Bool,
624
      fetchShadowPkgs       :: Flag Bool,
Andres Löh's avatar
Andres Löh committed
625
      fetchStrongFlags      :: Flag Bool,
626
627
628
629
630
631
632
633
      fetchVerbosity :: Flag Verbosity
    }

defaultFetchFlags :: FetchFlags
defaultFetchFlags = FetchFlags {
--  fetchOutput    = mempty,
    fetchDeps      = toFlag True,
    fetchDryRun    = toFlag False,
634
635
    fetchSolver           = Flag defaultSolver,
    fetchMaxBackjumps     = Flag defaultMaxBackjumps,
636
    fetchReorderGoals     = Flag False,
637
    fetchIndependentGoals = Flag False,
638
    fetchShadowPkgs       = Flag False,
Andres Löh's avatar
Andres Löh committed
639
    fetchStrongFlags      = Flag False,
640
641
642
643
    fetchVerbosity = toFlag normal
   }

fetchCommand :: CommandUI FetchFlags
Duncan Coutts's avatar
Duncan Coutts committed
644
645
fetchCommand = CommandUI {
    commandName         = "fetch",
646
    commandSynopsis     = "Downloads packages for later installation.",
647
648
649
650
651
    commandUsage        = usageAlternatives "fetch" [ "[FLAGS] PACKAGES"
                                                    ],
    commandDescription  = Just $ \_ ->
          "Note that it currently is not possible to fetch the dependencies for a\n"
       ++ "package in the current directory.\n",
652
    commandNotes        = Nothing,
653
    commandDefaultFlags = defaultFetchFlags,
654
    commandOptions      = \ showOrParseArgs -> [
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
         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
676
677
678
679

       ] ++

       optionSolver      fetchSolver           (\v flags -> flags { fetchSolver           = v }) :
680
681
       optionSolverFlags showOrParseArgs
                         fetchMaxBackjumps     (\v flags -> flags { fetchMaxBackjumps     = v })
682
683
                         fetchReorderGoals     (\v flags -> flags { fetchReorderGoals     = v })
                         fetchIndependentGoals (\v flags -> flags { fetchIndependentGoals = v })
684
                         fetchShadowPkgs       (\v flags -> flags { fetchShadowPkgs       = v })
Andres Löh's avatar
Andres Löh committed
685
                         fetchStrongFlags      (\v flags -> flags { fetchStrongFlags      = v })
686

Duncan Coutts's avatar
Duncan Coutts committed
687
688
  }

689
690
691
692
693
694
-- ------------------------------------------------------------
-- * Freeze command
-- ------------------------------------------------------------

data FreezeFlags = FreezeFlags {
      freezeDryRun           :: Flag Bool,
695
696
      freezeTests            :: Flag Bool,
      freezeBenchmarks       :: Flag Bool,
697
698
699
700
701
      freezeSolver           :: Flag PreSolver,
      freezeMaxBackjumps     :: Flag Int,
      freezeReorderGoals     :: Flag Bool,
      freezeIndependentGoals :: Flag Bool,
      freezeShadowPkgs       :: Flag Bool,
Andres Löh's avatar
Andres Löh committed
702
      freezeStrongFlags      :: Flag Bool,
703
704
705
706
707
708
      freezeVerbosity        :: Flag Verbosity
    }

defaultFreezeFlags :: FreezeFlags
defaultFreezeFlags = FreezeFlags {
    freezeDryRun           = toFlag False,
709
710
    freezeTests            = toFlag False,
    freezeBenchmarks       = toFlag False,
711
712
    freezeSolver           = Flag defaultSolver,
    freezeMaxBackjumps     = Flag defaultMaxBackjumps,
713
    freezeReorderGoals     = Flag False,
714
715
    freezeIndependentGoals = Flag False,
    freezeShadowPkgs       = Flag False,
Andres Löh's avatar
Andres Löh committed
716
    freezeStrongFlags      = Flag False,
717
718
719
720
721
722
723
    freezeVerbosity        = toFlag normal
   }

freezeCommand :: CommandUI FreezeFlags
freezeCommand = CommandUI {
    commandName         = "freeze",
    commandSynopsis     = "Freeze dependencies.",
724
725
726
727
728
729
730
731
    commandDescription  = Just $ \_ -> wrapText $
         "Calculates a valid set of dependencies and their exact versions. "
      ++ "If successful, saves the result to the file `cabal.config`.\n"
      ++ "\n"
      ++ "The package versions specified in `cabal.config` will be used for "
      ++ "any future installs.\n"
      ++ "\n"
      ++ "An existing `cabal.config` is ignored and overwritten.\n",
732
    commandNotes        = Nothing,
733
734
735
    commandUsage        = usageAlternatives "freeze" [""
                                                     ,"PACKAGES"
                                                     ],
736
737
738
739
740
741
742
743
744
    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

745
746
747
748
749
750
751
752
753
754
       , 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 [] [])

755
756
757
758
759
760
761
762
       ] ++

       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
763
                         freezeStrongFlags      (\v flags -> flags { freezeStrongFlags      = v })
764
765
766

  }

767
768
769
770
-- ------------------------------------------------------------
-- * Other commands
-- ------------------------------------------------------------

771
updateCommand  :: CommandUI (Flag Verbosity)
Duncan Coutts's avatar
Duncan Coutts committed
772
773
updateCommand = CommandUI {
    commandName         = "update",
774
    commandSynopsis     = "Updates list of known packages.",
775
776
777
    commandDescription  = Just $ \_ ->
      "For all known remote repositories, download the package list.\n",
    commandNotes        = Just $ \_ ->
778
779
780
      relevantConfigValuesText ["remote-repo"
                               ,"remote-repo-cache"
                               ,"local-repo"],
refold's avatar
refold committed
781
    commandUsage        = usageFlags "update",
782
    commandDefaultFlags = toFlag normal,
783
    commandOptions      = \_ -> [optionVerbosity id const]
Duncan Coutts's avatar
Duncan Coutts committed
784
785
  }

786
upgradeCommand  :: CommandUI (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags)
787
upgradeCommand = configureCommand {
ijones's avatar
ijones committed
788
    commandName         = "upgrade",
789
    commandSynopsis     = "(command disabled, use install instead)",
ijones's avatar
ijones committed
790
    commandDescription  = Nothing,
refold's avatar
refold committed
791
    commandUsage        = usageFlagsOrPackages "upgrade",
792
    commandDefaultFlags = (mempty, mempty, mempty, mempty),
793
    commandOptions      = commandOptions installCommand
ijones's avatar
ijones committed
794
795
  }

Duncan Coutts's avatar
Duncan Coutts committed
796
797
798
799
800
801
802
803
804
805
806
{-
cleanCommand  :: CommandUI ()
cleanCommand = makeCommand name shortDesc longDesc emptyFlags options
  where
    name       = "clean"
    shortDesc  = "Removes downloaded files"
    longDesc   = Nothing
    emptyFlags = ()
    options _  = []
-}

807
808
809
checkCommand  :: CommandUI (Flag Verbosity)
checkCommand = CommandUI {
    commandName         = "check",
810
    commandSynopsis     = "Check the package for common mistakes.",
811
812
813
814
815
816
    commandDescription  = Just $ \_ -> wrapText $
         "Expects a .cabal package file in the current directory.\n"
      ++ "\n"
      ++ "The checks correspond to the requirements to packages on Hackage. "
      ++ "If no errors and warnings are reported, Hackage will accept this "
      ++ "package.\n",
817
    commandNotes        = Nothing,
818
    commandUsage        = \pname -> "Usage: " ++ pname ++ " check\n",
819
    commandDefaultFlags = toFlag normal,
820
    commandOptions      = \_ -> []
821
822
  }

823
824
825
826
827
formatCommand  :: CommandUI (Flag Verbosity)
formatCommand = CommandUI {
    commandName         = "format",
    commandSynopsis     = "Reformat the .cabal file using the standard style.",
    commandDescription  = Nothing,
828
    commandNotes        = Nothing,
829
    commandUsage        = usageAlternatives "format" ["[FILE]"],
830
831
832
833
    commandDefaultFlags = toFlag normal,
    commandOptions      = \_ -> []
  }

834
runCommand :: CommandUI (BuildFlags, BuildExFlags)
refold's avatar
refold committed
835
836
runCommand = CommandUI {
    commandName         = "run",
837
838
839
840
841
    commandSynopsis     = "Builds and runs an executable.",
    commandDescription  = Just $ \_ -> wrapText $
         "Builds and then runs the specified executable. If no executable is "
      ++ "specified, but the package contains just one executable, that one "
      ++ "is built and executed.\n",
842
    commandNotes        = Nothing,
843
844
    commandUsage        = usageAlternatives "run"
        ["[FLAGS] [EXECUTABLE] [-- EXECUTABLE_FLAGS]"],
refold's avatar
refold committed
845
    commandDefaultFlags = mempty,
846
847
    commandOptions      =
      \showOrParseArgs -> liftOptions fst setFst
848
                          (commandOptions parent showOrParseArgs)
849
850
851
                          ++
                          liftOptions snd setSnd
                          (buildExOptions showOrParseArgs)
refold's avatar
refold committed
852
853
  }
  where
854
855
856
    setFst a (_,b) = (a,b)
    setSnd b (a,_) = (a,b)

857
    parent = Cabal.buildCommand defaultProgramConfiguration
refold's avatar
refold committed
858

859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
-- ------------------------------------------------------------
-- * 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
877
878
879
reportCommand = CommandUI {
    commandName         = "report",
    commandSynopsis     = "Upload build reports to a remote server.",
880
881
    commandDescription  = Nothing,
    commandNotes        = Just $ \_ ->
882
         "You can store your Hackage login in the ~/.cabal/config file\n",
883
    commandUsage        = usageAlternatives "report" ["[FLAGS]"],
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
    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))
      ]
900
901
  }

902
903
904
905
906
907
908
909
910
911
912
913
914
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

915
-- ------------------------------------------------------------
916
-- * Get flags
917
918
-- ------------------------------------------------------------

919
920
921
922
923
924
data GetFlags = GetFlags {
    getDestDir          :: Flag FilePath,
    getPristine         :: Flag Bool,
    getSourceRepository :: Flag (Maybe RepoKind),
    getVerbosity        :: Flag Verbosity
  }
925

926
927
928
929
930
931
defaultGetFlags :: GetFlags
defaultGetFlags = GetFlags {
    getDestDir          = mempty,
    getPristine         = mempty,
    getSourceRepository = mempty,
    getVerbosity        = toFlag normal
932
933
   }

934
935
936
getCommand :: CommandUI GetFlags
getCommand = CommandUI {
    commandName         = "get",
937
938
    commandSynopsis     = "Download/Extract a package's source code (repository).",
    commandDescription  = Just $ \_ -> wrapText $
939
940
941
942
          "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",
943
    commandNotes        = Nothing,
944
    commandUsage        = usagePackages "get",
945
    commandDefaultFlags = defaultGetFlags,
946
    commandOptions      = \_ -> [
947
        optionVerbosity getVerbosity (\v flags -> flags { getVerbosity = v })
948
949

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

954
       ,option "s" ["source-repository"]
955
         "Copy the package's source repository (ie git clone, darcs get, etc as appropriate)."
956
957
958
959
960
961
         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))

962
963
964
       , option [] ["pristine"]
           ("Unpack the original pristine tarball, rather than updating the "
           ++ ".cabal file with the latest revision from the package archive.")
965
           getPristine (\v flags -> flags { getPristine = v })
966
           trueArg
967
968
969
       ]
  }

970
971
972
973
974
975
976
-- 'cabal unpack' is a deprecated alias for 'cabal get'.
unpackCommand :: CommandUI GetFlags
unpackCommand = getCommand {
  commandName  = "unpack",
  commandUsage = usagePackages "unpack"
  }

977
instance Monoid GetFlags where
978
979
980
981
982
983
  mempty = GetFlags {
    getDestDir          = mempty,
    getPristine         = mempty,
    getSourceRepository = mempty,
    getVerbosity        = mempty
    }
984
985
986
987
988
  mappend a b = GetFlags {
    getDestDir          = combine getDestDir,
    getPristine         = combine getPristine,
    getSourceRepository = combine getSourceRepository,
    getVerbosity        = combine getVerbosity
989
990
991
  }
    where combine field = field a `mappend` field b

992
993
994
995
996
-- ------------------------------------------------------------
-- * List flags
-- ------------------------------------------------------------

data ListFlags = ListFlags {
997
    listInstalled    :: Flag Bool,
998
    listSimpleOutput :: Flag Bool,
999
1000
    listVerbosity    :: Flag Verbosity,
    listPackageDBs   :: [Maybe PackageDB]