Setup.hs 84.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
    , uninstallCommand
26
    , infoCommand, InfoFlags(..)
27
    , fetchCommand, FetchFlags(..)
28
    , freezeCommand, FreezeFlags(..)
29
    , getCommand, unpackCommand, GetFlags(..)
30
    , checkCommand
31
    , formatCommand
32
    , uploadCommand, UploadFlags(..)
33
    , reportCommand, ReportFlags(..)
refold's avatar
refold committed
34
    , runCommand
35
    , initCommand, IT.InitFlags(..)
36
    , sdistCommand, SDistFlags(..), SDistExFlags(..), ArchiveFormat(..)
37
    , win32SelfUpgradeCommand, Win32SelfUpgradeFlags(..)
refold's avatar
refold committed
38
    , sandboxCommand, defaultSandboxLocation, SandboxFlags(..)
39
    , execCommand, ExecFlags(..)
40
    , userConfigCommand, UserConfigFlags(..)
Duncan Coutts's avatar
Duncan Coutts committed
41
42

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

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

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

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

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

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

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

145
146
globalCommand :: [Command action] -> CommandUI GlobalFlags
globalCommand commands = CommandUI {
147
    commandName         = "",
148
149
    commandSynopsis     =
         "Command line interface to the Haskell Cabal infrastructure.",
150
151
152
153
    commandUsage        = \pname ->
         "See http://www.haskell.org/cabal/ for more information.\n"
      ++ "\n"
      ++ "Usage: " ++ pname ++ " [GLOBAL FLAGS] [COMMAND [FLAGS]]\n",
154
    commandDescription  = Just $ \pname ->
155
156
157
      let
        commands' = commands ++ [commandAddAction helpCommandUI undefined]
        cmdDescs = getNormalCommandDescriptions commands'
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
192
        -- 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"
          ]
193
194
        maxlen    = maximum $ [length name | (name, _) <- cmdDescs]
        align str = str ++ replicate (maxlen - length str) ' '
195
196
197
198
199
200
201
202
203
        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
204
205
      in
         "Commands:\n"
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
241
      ++ 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"
242
        , addCmd "sandbox"
243
244
245
246
247
        , addCmd "exec"
        , addCmdCustom "repl" "Open interpreter with access to sandbox packages."
        ] ++ if null otherCmds then [] else par
                                           :startGroup "other"
                                           :[addCmd n | n <- otherCmds])
248
249
      ++ "\n"
      ++ "For more information about a command use:\n"
250
251
      ++ "   " ++ pname ++ " COMMAND --help\n"
      ++ "or " ++ pname ++ " help COMMAND\n"
252
      ++ "\n"
253
      ++ "To install Cabal packages from hackage use:\n"
254
255
      ++ "  " ++ pname ++ " install foo [--dry-run]\n"
      ++ "\n"
256
257
      ++ "Occasionally you need to update the list of available packages:\n"
      ++ "  " ++ pname ++ " update\n",
258
    commandNotes = Nothing,
259
    commandDefaultFlags = mempty,
260
    commandOptions      = \showOrParseArgs ->
261
      (case showOrParseArgs of ShowArgs -> take 6; ParseArgs -> id)
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
      [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")

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

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

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

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

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

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

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

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

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

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

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

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

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

389
390
391
    -- Cabal < 1.22 doesn't know about '--disable-debug-info'.
    flags_1_21_0 = flags_latest { configDebugInfo = NoFlag }

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

421
422
423
424
425
426
427
428
-- ------------------------------------------------------------
-- * Config extra flags
-- ------------------------------------------------------------

-- | cabal configure takes some extra flags beyond runghc Setup configure
--
data ConfigExFlags = ConfigExFlags {
    configCabalVersion :: Flag Version,
429
    configExConstraints:: [UserConstraint],
430
    configPreferences  :: [Dependency],
431
432
    configSolver       :: Flag PreSolver,
    configAllowNewer   :: Flag AllowNewer
433
434
435
  }

defaultConfigExFlags :: ConfigExFlags
436
437
defaultConfigExFlags = mempty { configSolver     = Flag defaultSolver
                              , configAllowNewer = Flag AllowNewerNone }
438
439
440
441
442

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

  , option [] ["preference"]
      "Specify preferences (soft constraints) on the version of a package"
      configPreferences (\v flags -> flags { configPreferences = v })
471
472
473
474
      (reqArg "CONSTRAINT"
              (readP_to_E (const "dependency expected")
                          (fmap (\x -> [x]) parse))
              (map display))
475
476

  , optionSolver configSolver (\v flags -> flags { configSolver = v })
477
478

  , option [] ["allow-newer"]
cheecheeo's avatar
cheecheeo committed
479
    ("Ignore upper bounds in all dependencies or " ++ allowNewerArgument)
480
    configAllowNewer (\v flags -> flags { configAllowNewer = v})
cheecheeo's avatar
cheecheeo committed
481
    (optArg allowNewerArgument
482
483
484
     (fmap Flag allowNewerParser) (Flag AllowNewerAll)
     allowNewerPrinter)

485
  ]
cheecheeo's avatar
cheecheeo committed
486
  where allowNewerArgument = "DEPS"
487
488
489
490

instance Monoid ConfigExFlags where
  mempty = ConfigExFlags {
    configCabalVersion = mempty,
491
    configExConstraints= mempty,
492
    configPreferences  = mempty,
493
494
    configSolver       = mempty,
    configAllowNewer   = mempty
495
496
497
  }
  mappend a b = ConfigExFlags {
    configCabalVersion = combine configCabalVersion,
498
    configExConstraints= combine configExConstraints,
499
    configPreferences  = combine configPreferences,
500
501
    configSolver       = combine configSolver,
    configAllowNewer   = combine configAllowNewer
502
503
504
  }
    where combine field = field a `mappend` field b

ttuegel's avatar
ttuegel committed
505
506
507
508
-- ------------------------------------------------------------
-- * Build flags
-- ------------------------------------------------------------

509
510
511
512
513
514
515
516
517
518
data SkipAddSourceDepsCheck =
  SkipAddSourceDepsCheck | DontSkipAddSourceDepsCheck
  deriving Eq

data BuildExFlags = BuildExFlags {
  buildOnly     :: Flag SkipAddSourceDepsCheck
}

buildExOptions :: ShowOrParseArgs -> [OptionField BuildExFlags]
buildExOptions _showOrParseArgs =
519
  option [] ["only"]
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
  "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

-- ------------------------------------------------------------
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
-- * 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

569
570
571
572
-- ------------------------------------------------------------
-- * Test command
-- ------------------------------------------------------------

573
testCommand :: CommandUI (TestFlags, BuildFlags, BuildExFlags)
574
testCommand = parent {
575
576
  commandDefaultFlags = (commandDefaultFlags parent,
                         Cabal.defaultBuildFlags, mempty),
577
  commandOptions      =
578
    \showOrParseArgs -> liftOptions get1 set1
579
580
                        (commandOptions parent showOrParseArgs)
                        ++
581
582
583
584
                        liftOptions get2 set2
                        (Cabal.buildOptions progConf showOrParseArgs)
                        ++
                        liftOptions get3 set3 (buildExOptions showOrParseArgs)
585
586
  }
  where
587
588
589
    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)
590

591
592
    parent   = Cabal.testCommand
    progConf = defaultProgramConfiguration
593
594
595
596
597

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

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

616
617
    parent   = Cabal.benchmarkCommand
    progConf = defaultProgramConfiguration
ttuegel's avatar
ttuegel committed
618

619
-- ------------------------------------------------------------
620
-- * Fetch command
621
-- ------------------------------------------------------------
622

623
624
625
626
data FetchFlags = FetchFlags {
--    fetchOutput    :: Flag FilePath,
      fetchDeps      :: Flag Bool,
      fetchDryRun    :: Flag Bool,
627
      fetchSolver           :: Flag PreSolver,
628
629
630
      fetchMaxBackjumps     :: Flag Int,
      fetchReorderGoals     :: Flag Bool,
      fetchIndependentGoals :: Flag Bool,
631
      fetchShadowPkgs       :: Flag Bool,
Andres Löh's avatar
Andres Löh committed
632
      fetchStrongFlags      :: Flag Bool,
633
634
635
636
637
638
639
640
      fetchVerbosity :: Flag Verbosity
    }

defaultFetchFlags :: FetchFlags
defaultFetchFlags = FetchFlags {
--  fetchOutput    = mempty,
    fetchDeps      = toFlag True,
    fetchDryRun    = toFlag False,
641
642
    fetchSolver           = Flag defaultSolver,
    fetchMaxBackjumps     = Flag defaultMaxBackjumps,
643
    fetchReorderGoals     = Flag False,
644
    fetchIndependentGoals = Flag False,
645
    fetchShadowPkgs       = Flag False,
Andres Löh's avatar
Andres Löh committed
646
    fetchStrongFlags      = Flag False,
647
648
649
650
    fetchVerbosity = toFlag normal
   }

fetchCommand :: CommandUI FetchFlags
Duncan Coutts's avatar
Duncan Coutts committed
651
652
fetchCommand = CommandUI {
    commandName         = "fetch",
653
    commandSynopsis     = "Downloads packages for later installation.",
654
655
656
657
658
    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",
659
    commandNotes        = Nothing,
660
    commandDefaultFlags = defaultFetchFlags,
661
    commandOptions      = \ showOrParseArgs -> [
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
         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
683
684
685
686

       ] ++

       optionSolver      fetchSolver           (\v flags -> flags { fetchSolver           = v }) :
687
688
       optionSolverFlags showOrParseArgs
                         fetchMaxBackjumps     (\v flags -> flags { fetchMaxBackjumps     = v })
689
690
                         fetchReorderGoals     (\v flags -> flags { fetchReorderGoals     = v })
                         fetchIndependentGoals (\v flags -> flags { fetchIndependentGoals = v })
691
                         fetchShadowPkgs       (\v flags -> flags { fetchShadowPkgs       = v })
Andres Löh's avatar
Andres Löh committed
692
                         fetchStrongFlags      (\v flags -> flags { fetchStrongFlags      = v })
693

Duncan Coutts's avatar
Duncan Coutts committed
694
695
  }

696
697
698
699
700
701
-- ------------------------------------------------------------
-- * Freeze command
-- ------------------------------------------------------------

data FreezeFlags = FreezeFlags {
      freezeDryRun           :: Flag Bool,
702
703
      freezeTests            :: Flag Bool,
      freezeBenchmarks       :: Flag Bool,
704
705
706
707
708
      freezeSolver           :: Flag PreSolver,
      freezeMaxBackjumps     :: Flag Int,
      freezeReorderGoals     :: Flag Bool,
      freezeIndependentGoals :: Flag Bool,
      freezeShadowPkgs       :: Flag Bool,
Andres Löh's avatar
Andres Löh committed
709
      freezeStrongFlags      :: Flag Bool,
710
711
712
713
714
715
      freezeVerbosity        :: Flag Verbosity
    }

defaultFreezeFlags :: FreezeFlags
defaultFreezeFlags = FreezeFlags {
    freezeDryRun           = toFlag False,
716
717
    freezeTests            = toFlag False,
    freezeBenchmarks       = toFlag False,
718
719
    freezeSolver           = Flag defaultSolver,
    freezeMaxBackjumps     = Flag defaultMaxBackjumps,
720
    freezeReorderGoals     = Flag False,
721
722
    freezeIndependentGoals = Flag False,
    freezeShadowPkgs       = Flag False,
Andres Löh's avatar
Andres Löh committed
723
    freezeStrongFlags      = Flag False,
724
725
726
727
728
729
730
    freezeVerbosity        = toFlag normal
   }

freezeCommand :: CommandUI FreezeFlags
freezeCommand = CommandUI {
    commandName         = "freeze",
    commandSynopsis     = "Freeze dependencies.",
731
732
733
734
735
736
737
738
    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",
739
    commandNotes        = Nothing,
740
    commandUsage        = usageFlags "freeze",
741
742
743
744
745
746
747
748
749
    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

750
751
752
753
754
755
756
757
758
759
       , 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 [] [])

760
761
762
763
764
765
766
767
       ] ++

       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
768
                         freezeStrongFlags      (\v flags -> flags { freezeStrongFlags      = v })
769
770
771

  }

772
773
774
775
-- ------------------------------------------------------------
-- * Other commands
-- ------------------------------------------------------------

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

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

Duncan Coutts's avatar
Duncan Coutts committed
801
802
803
804
805
806
807
808
809
810
811
{-
cleanCommand  :: CommandUI ()
cleanCommand = makeCommand name shortDesc longDesc emptyFlags options
  where
    name       = "clean"
    shortDesc  = "Removes downloaded files"
    longDesc   = Nothing
    emptyFlags = ()
    options _  = []
-}

812
813
814
checkCommand  :: CommandUI (Flag Verbosity)
checkCommand = CommandUI {
    commandName         = "check",
815
    commandSynopsis     = "Check the package for common mistakes.",
816
817
818
819
820
821
    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",
822
    commandNotes        = Nothing,
823
    commandUsage        = \pname -> "Usage: " ++ pname ++ " check\n",
824
    commandDefaultFlags = toFlag normal,
825
    commandOptions      = \_ -> []
826
827
  }

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

839
840
841
842
843
844
845
846
847
848
849
uninstallCommand  :: CommandUI (Flag Verbosity)
uninstallCommand = CommandUI {
    commandName         = "uninstall",
    commandSynopsis     = "Warn about 'uninstall' not being implemented.",
    commandDescription  = Nothing,
    commandNotes        = Nothing,
    commandUsage        = usageAlternatives "uninstall" ["PACKAGES"],
    commandDefaultFlags = toFlag normal,
    commandOptions      = \_ -> []
  }

850
runCommand :: CommandUI (BuildFlags, BuildExFlags)
refold's avatar
refold committed
851
852
runCommand = CommandUI {
    commandName         = "run",
853
854
855
856
857
    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",
858
    commandNotes        = Nothing,
859
860
    commandUsage        = usageAlternatives "run"
        ["[FLAGS] [EXECUTABLE] [-- EXECUTABLE_FLAGS]"],
refold's avatar
refold committed
861
    commandDefaultFlags = mempty,
862
863
    commandOptions      =
      \showOrParseArgs -> liftOptions fst setFst
864
                          (commandOptions parent showOrParseArgs)
865
866
867
                          ++
                          liftOptions snd setSnd
                          (buildExOptions showOrParseArgs)
refold's avatar
refold committed
868
869
  }
  where
870
871
872
    setFst a (_,b) = (a,b)
    setSnd b (a,_) = (a,b)

873
    parent = Cabal.buildCommand defaultProgramConfiguration
refold's avatar
refold committed
874

875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
-- ------------------------------------------------------------
-- * 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
893
894
895
reportCommand = CommandUI {
    commandName         = "report",
    commandSynopsis     = "Upload build reports to a remote server.",
896
897
    commandDescription  = Nothing,
    commandNotes        = Just $ \_ ->
898
         "You can store your Hackage login in the ~/.cabal/config file\n",
899
    commandUsage        = usageAlternatives "report" ["[FLAGS]"],
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
    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))
      ]
916
917
  }

918
919
920
921
922
923
924
925
926
927
928
929
930
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

931
-- ------------------------------------------------------------
932
-- * Get flags
933
934
-- ------------------------------------------------------------

935
936
937
938
939
940
data GetFlags = GetFlags {
    getDestDir          :: Flag FilePath,
    getPristine         :: Flag Bool,
    getSourceRepository :: Flag (Maybe RepoKind),
    getVerbosity        :: Flag Verbosity
  }
941

942
943
944
945
946
947
defaultGetFlags :: GetFlags
defaultGetFlags = GetFlags {
    getDestDir          = mempty,
    getPristine         = mempty,
    getSourceRepository = mempty,
    getVerbosity        = toFlag normal
948
949
   }

950
951
952
getCommand :: CommandUI GetFlags
getCommand = CommandUI {
    commandName         = "get",
953
954
    commandSynopsis     = "Download/Extract a package's source code (repository).",
    commandDescription  = Just $ \_ -> wrapText $
955
956
957
958
          "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",
959
    commandNotes        = Nothing,
960
    commandUsage        = usagePackages "get",
961
    commandDefaultFlags = defaultGetFlags,
962
    commandOptions      = \_ -> [
963
        optionVerbosity getVerbosity (\v flags -> flags { getVerbosity = v })
964
965

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

970
       ,option "s" ["source-repository"]
971
         "Copy the package's source repository (ie git clone, darcs get, etc as appropriate)."
972
973
974
975
976
977
         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))

978
979
980
       , option [] ["pristine"]
           ("Unpack the original pristine tarball, rather than updating the "
           ++ ".cabal file with the latest revision from the package archive.")
981
           getPristine (\v flags -> flags { getPristine = v })
982
           trueArg
983
984
985
       ]
  }

986
987
988
989
990
991
992
-- 'cabal unpack' is a deprecated alias for 'cabal get'.
unpackCommand :: CommandUI GetFlags
unpackCommand = getCommand {
  commandName  = "unpack",
  commandUsage = usagePackages "unpack"
  }

993
instance Monoid GetFlags where
994
995
996
997
998
999
  mempty = GetFlags {
    getDestDir          = mempty,
    getPristine         = mempty,
    getSourceRepository = mempty,
    getVerbosity        = mempty
    }
1000
  mappend a b = GetFlags {