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

    , parsePackageArgs
51
52
53
    --TODO: stop exporting these:
    , showRepo
    , parseRepo
54
    , readRepo
55
56
    ) where

57
import Distribution.Client.Types
Edsko de Vries's avatar
Edsko de Vries committed
58
         ( Username(..), Password(..), RemoteRepo(..) )
59
60
import Distribution.Client.BuildReports.Types
         ( ReportLevel(..) )
61
import Distribution.Client.Dependency.Types
62
         ( PreSolver(..), ConstraintSource(..) )
63
64
import qualified Distribution.Client.Init.Types as IT
         ( InitFlags(..), PackageType(..) )
65
66
import Distribution.Client.Targets
         ( UserConstraint, readUserConstraint )
67
68
import Distribution.Utils.NubList
         ( NubList, toNubList, fromNubList)
69

70

71
import Distribution.Simple.Compiler (PackageDB)
72
73
import Distribution.Simple.Program
         ( defaultProgramConfiguration )
74
75
import Distribution.Simple.Command hiding (boolOpt, boolOpt')
import qualified Distribution.Simple.Command as Command
Duncan Coutts's avatar
Duncan Coutts committed
76
import qualified Distribution.Simple.Setup as Cabal
77
import Distribution.Simple.Setup
78
79
         ( ConfigFlags(..), BuildFlags(..), ReplFlags
         , TestFlags(..), BenchmarkFlags(..)
80
         , SDistFlags(..), HaddockFlags(..)
81
         , readPackageDbList, showPackageDbList
Edsko de Vries's avatar
Edsko de Vries committed
82
         , Flag(..), toFlag, flagToMaybe, flagToList
83
84
         , optionVerbosity, boolOpt, boolOpt', trueArg, falseArg
         , readPToMaybe, optionNumJobs )
85
import Distribution.Simple.InstallDirs
86
87
         ( PathTemplate, InstallDirs(sysconfdir)
         , toPathTemplate, fromPathTemplate )
88
import Distribution.Version
Duncan Coutts's avatar
Duncan Coutts committed
89
         ( Version(Version), anyVersion, thisVersion )
90
import Distribution.Package
91
         ( PackageIdentifier, packageName, packageVersion, Dependency(..) )
92
import Distribution.PackageDescription
93
         ( BuildType(..), RepoKind(..) )
94
import Distribution.Text
95
         ( Text(..), display )
96
import Distribution.ReadE
97
         ( ReadE(..), readP_to_E, succeedReadE )
98
import qualified Distribution.Compat.ReadP as Parse
99
         ( ReadP, char, munch1, pfail,  (+++) )
100
import Distribution.Compat.Semigroup
101
102
import Distribution.Verbosity
         ( Verbosity, normal )
103
import Distribution.Simple.Utils
104
         ( wrapText, wrapLine )
105
import Distribution.Client.GlobalFlags
Edsko de Vries's avatar
Edsko de Vries committed
106
107
108
         ( GlobalFlags(..), defaultGlobalFlags
         , RepoContext(..), withRepoContext
         )
109

110
import Data.Char
111
         ( isAlphaNum )
112
import Data.List
113
         ( intercalate, deleteFirstsBy )
114
import Data.Maybe
115
         ( maybeToList, fromMaybe )
116
117
import GHC.Generics (Generic)
import Distribution.Compat.Binary (Binary)
118
119
120
121
122
123
import Control.Monad
         ( liftM )
import System.FilePath
         ( (</>) )
import Network.URI
         ( parseAbsoluteURI, uriToString )
124

125
126
globalCommand :: [Command action] -> CommandUI GlobalFlags
globalCommand commands = CommandUI {
127
    commandName         = "",
128
129
    commandSynopsis     =
         "Command line interface to the Haskell Cabal infrastructure.",
130
131
132
133
    commandUsage        = \pname ->
         "See http://www.haskell.org/cabal/ for more information.\n"
      ++ "\n"
      ++ "Usage: " ++ pname ++ " [GLOBAL FLAGS] [COMMAND [FLAGS]]\n",
134
    commandDescription  = Just $ \pname ->
135
136
137
      let
        commands' = commands ++ [commandAddAction helpCommandUI undefined]
        cmdDescs = getNormalCommandDescriptions commands'
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
        -- 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"
166
          , "gen-bounds"
167
168
169
170
171
172
173
          , "haddock"
          , "hscolour"
          , "copy"
          , "register"
          , "sandbox"
          , "exec"
          ]
174
175
        maxlen    = maximum $ [length name | (name, _) <- cmdDescs]
        align str = str ++ replicate (maxlen - length str) ' '
176
177
178
179
180
181
182
183
184
        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
185
186
      in
         "Commands:\n"
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
      ++ 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"
217
        , addCmd "gen-bounds"
218
219
220
221
222
223
        , addCmd "haddock"
        , addCmd "hscolour"
        , addCmd "copy"
        , addCmd "register"
        , par
        , startGroup "sandbox"
224
        , addCmd "sandbox"
225
226
227
228
229
        , addCmd "exec"
        , addCmdCustom "repl" "Open interpreter with access to sandbox packages."
        ] ++ if null otherCmds then [] else par
                                           :startGroup "other"
                                           :[addCmd n | n <- otherCmds])
230
231
      ++ "\n"
      ++ "For more information about a command use:\n"
232
233
      ++ "   " ++ pname ++ " COMMAND --help\n"
      ++ "or " ++ pname ++ " help COMMAND\n"
234
      ++ "\n"
235
      ++ "To install Cabal packages from hackage use:\n"
236
237
      ++ "  " ++ pname ++ " install foo [--dry-run]\n"
      ++ "\n"
238
239
      ++ "Occasionally you need to update the list of available packages:\n"
      ++ "  " ++ pname ++ " update\n",
240
    commandNotes = Nothing,
241
    commandDefaultFlags = mempty,
242
243
244
245
246
247
248
249
250
251
252
    commandOptions = args
  }
  where
    args :: ShowOrParseArgs -> [OptionField GlobalFlags]
    args ShowArgs  = argsShown
    args ParseArgs = argsShown ++ argsNotShown

    -- arguments we want to show in the help
    argsShown :: [OptionField GlobalFlags]
    argsShown = [
       option ['V'] ["version"]
253
254
255
256
257
258
259
260
261
262
263
264
265
266
         "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")

267
      ,option [] ["sandbox-config-file"]
268
         "Set an alternate location for the sandbox config file (default: './cabal.sandbox.config')"
269
         globalSandboxConfigFile (\v flags -> flags { globalSandboxConfigFile = v })
270
271
         (reqArgFlag "FILE")

U-CIQDEV\gbazerman's avatar
U-CIQDEV\gbazerman committed
272
273
      ,option [] ["default-user-config"]
         "Set a location for a cabal.config file for projects without their own cabal.config freeze file."
274
         globalConstraintsFile (\v flags -> flags {globalConstraintsFile = v})
U-CIQDEV\gbazerman's avatar
U-CIQDEV\gbazerman committed
275
276
         (reqArgFlag "FILE")

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

282
283
284
285
286
      ,option [] ["ignore-sandbox"]
         "Ignore any existing sandbox"
         globalIgnoreSandbox (\v flags -> flags { globalIgnoreSandbox = v })
         trueArg

287
      ,option [] ["ignore-expiry"]
Edsko de Vries's avatar
Edsko de Vries committed
288
         "Ignore expiry dates on signed metadata (use only in exceptional circumstances)"
289
290
291
         globalIgnoreExpiry (\v flags -> flags { globalIgnoreExpiry = v })
         trueArg

292
      ,option [] ["http-transport"]
293
         "Set a transport for http(s) requests. Accepts 'curl', 'wget', 'powershell', and 'plain-http'. (default: 'curl')"
294
         globalHttpTransport (\v flags -> flags { globalHttpTransport = v })
295
         (reqArgFlag "HttpTransport")
296
      ]
297

298
299
300
301
    -- arguments we don't want shown in the help
    argsNotShown :: [OptionField GlobalFlags]
    argsNotShown = [
       option [] ["remote-repo"]
302
303
         "The name and url for a remote repository"
         globalRemoteRepos (\v flags -> flags { globalRemoteRepos = v })
304
         (reqArg' "NAME:URL" (toNubList . maybeToList . readRepo) (map showRepo . fromNubList))
305
306
307
308
309
310
311
312
313

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

316
317
318
319
320
      ,option [] ["logs-dir"]
         "The location to put log files"
         globalLogsDir (\v flags -> flags { globalLogsDir = v })
         (reqArgFlag "DIR")

321
322
323
324
      ,option [] ["world-file"]
         "The location of the world file"
         globalWorldFile (\v flags -> flags { globalWorldFile = v })
         (reqArgFlag "FILE")
325
326
327
328
329
      ]

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

331
configureCommand :: CommandUI ConfigFlags
332
333
configureCommand = c
  { commandDefaultFlags = mempty
334
335
336
  , commandNotes = Just $ \pname -> (case commandNotes c of
         Nothing -> ""
         Just n  -> n pname ++ "\n")
337
338
339
340
341
342
       ++ "Examples:\n"
       ++ "  " ++ pname ++ " configure\n"
       ++ "    Configure with defaults;\n"
       ++ "  " ++ pname ++ " configure --enable-tests -fcustomflag\n"
       ++ "    Configure building package including tests,\n"
       ++ "    with some package-specific flag.\n"
Duncan Coutts's avatar
Duncan Coutts committed
343
  }
344
345
 where
  c = Cabal.configureCommand defaultProgramConfiguration
Duncan Coutts's avatar
Duncan Coutts committed
346

347
348
349
configureOptions ::  ShowOrParseArgs -> [OptionField ConfigFlags]
configureOptions = commandOptions configureCommand

350
filterConfigureFlags :: ConfigFlags -> Version -> ConfigFlags
351
filterConfigureFlags flags cabalLibVersion
352
  | cabalLibVersion >= Version [1,23,0] [] = flags_latest
353
  -- ^ NB: we expect the latest version to be the most common case.
354
355
  | cabalLibVersion <  Version [1,3,10] [] = flags_1_3_10
  | cabalLibVersion <  Version [1,10,0] [] = flags_1_10_0
356
  | cabalLibVersion <  Version [1,12,0] [] = flags_1_12_0
357
  | cabalLibVersion <  Version [1,14,0] [] = flags_1_14_0
358
  | cabalLibVersion <  Version [1,18,0] [] = flags_1_18_0
359
  | cabalLibVersion <  Version [1,19,1] [] = flags_1_19_0
360
  | cabalLibVersion <  Version [1,19,2] [] = flags_1_19_1
361
  | cabalLibVersion <  Version [1,21,1] [] = flags_1_20_0
362
  | cabalLibVersion <  Version [1,22,0] [] = flags_1_21_0
363
  | cabalLibVersion <  Version [1,23,0] [] = flags_1_22_0
364
  | otherwise = flags_latest
365
  where
366
367
368
369
370
    flags_latest = flags        {
      -- Cabal >= 1.19.1 uses '--dependency' and does not need '--constraint'.
      configConstraints = [],
      -- Passing '--allow-newer' to Setup.hs is unnecessary, we use
      -- '--exact-configuration' instead.
371
      configAllowNewer  = Just Cabal.AllowNewerNone
372
      }
373

374
375
    -- Cabal < 1.23 doesn't know about '--profiling-detail'.
    flags_1_22_0 = flags_latest { configProfDetail    = NoFlag
376
377
                                , configProfLibDetail = NoFlag
                                , configIPID          = NoFlag }
378

379
    -- Cabal < 1.22 doesn't know about '--disable-debug-info'.
380
    flags_1_21_0 = flags_1_22_0 { configDebugInfo = NoFlag }
381

382
    -- Cabal < 1.21.1 doesn't know about 'disable-relocatable'
383
384
    -- Cabal < 1.21.1 doesn't know about 'enable-profiling'
    flags_1_20_0 =
385
      flags_1_21_0 { configRelocatable = NoFlag
386
387
388
389
                   , configProf = NoFlag
                   , configProfExe = configProf flags
                   , configProfLib =
                     mappend (configProf flags) (configProfLib flags)
390
391
                   , configCoverage = NoFlag
                   , configLibCoverage = configCoverage flags
392
                   }
393
394
395
396
    -- 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 }
397
398
399
    -- Cabal < 1.19.1 uses '--constraint' instead of '--dependency'.
    flags_1_19_0 = flags_1_19_1 { configDependencies = []
                                , configConstraints  = configConstraints flags }
400
    -- Cabal < 1.18.0 doesn't know about --extra-prog-path and --sysconfdir.
401
    flags_1_18_0 = flags_1_19_0 { configProgramPathExtra = toNubList []
402
403
                                , configInstallDirs = configInstallDirs_1_18_0}
    configInstallDirs_1_18_0 = (configInstallDirs flags) { sysconfdir = NoFlag }
404
    -- Cabal < 1.14.0 doesn't know about '--disable-benchmarks'.
405
    flags_1_14_0 = flags_1_18_0 { configBenchmarks  = NoFlag }
406
407
408
409
    -- Cabal < 1.12.0 doesn't know about '--enable/disable-executable-dynamic'
    -- and '--enable/disable-library-coverage'.
    flags_1_12_0 = flags_1_14_0 { configLibCoverage = NoFlag
                                , configDynExe      = NoFlag }
410
    -- Cabal < 1.10.0 doesn't know about '--disable-tests'.
411
    flags_1_10_0 = flags_1_12_0 { configTests       = NoFlag }
412
    -- Cabal < 1.3.10 does not grok the '--constraints' flag.
413
    flags_1_3_10 = flags_1_10_0 { configConstraints = [] }
414

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

-- | cabal configure takes some extra flags beyond runghc Setup configure
--
data ConfigExFlags = ConfigExFlags {
    configCabalVersion :: Flag Version,
423
    configExConstraints:: [(UserConstraint, ConstraintSource)],
424
    configPreferences  :: [Dependency],
425
    configSolver       :: Flag PreSolver
426
  }
427
  deriving (Eq, Generic)
428
429

defaultConfigExFlags :: ConfigExFlags
430
defaultConfigExFlags = mempty { configSolver     = Flag defaultSolver }
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
      ++ liftOptions snd setSnd
         (configureExOptions showOrParseArgs ConstraintSourceCommandlineFlag)
441
442
443
444
445
  }
  where
    setFst a (_,b) = (a,b)
    setSnd b (a,_) = (a,b)

446
447
448
449
configureExOptions :: ShowOrParseArgs
                   -> ConstraintSource
                   -> [OptionField ConfigExFlags]
configureExOptions _showOrParseArgs src =
450
451
452
453
454
455
456
  [ 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))
457
458
459
460
  , option [] ["constraint"]
      "Specify constraints on a package (version, installed/source, flags)"
      configExConstraints (\v flags -> flags { configExConstraints = v })
      (reqArg "CONSTRAINT"
461
462
              ((\x -> [(x, src)]) `fmap` ReadE readUserConstraint)
              (map $ display . fst))
463
464
465
466

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

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

474
475
476
  ]

instance Monoid ConfigExFlags where
477
  mempty = gmempty
478
479
480
  mappend = (<>)

instance Semigroup ConfigExFlags where
481
  (<>) = gmappend
482

ttuegel's avatar
ttuegel committed
483
484
485
486
-- ------------------------------------------------------------
-- * Build flags
-- ------------------------------------------------------------

487
488
489
490
491
492
data SkipAddSourceDepsCheck =
  SkipAddSourceDepsCheck | DontSkipAddSourceDepsCheck
  deriving Eq

data BuildExFlags = BuildExFlags {
  buildOnly     :: Flag SkipAddSourceDepsCheck
493
} deriving Generic
494
495
496

buildExOptions :: ShowOrParseArgs -> [OptionField BuildExFlags]
buildExOptions _showOrParseArgs =
497
  option [] ["only"]
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
  "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
520
  mempty = gmempty
521
522
523
  mappend = (<>)

instance Semigroup BuildExFlags where
524
  (<>) = gmappend
525
526

-- ------------------------------------------------------------
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
-- * 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

545
546
547
548
-- ------------------------------------------------------------
-- * Test command
-- ------------------------------------------------------------

549
testCommand :: CommandUI (TestFlags, BuildFlags, BuildExFlags)
550
testCommand = parent {
551
552
  commandDefaultFlags = (commandDefaultFlags parent,
                         Cabal.defaultBuildFlags, mempty),
553
  commandOptions      =
554
    \showOrParseArgs -> liftOptions get1 set1
555
556
                        (commandOptions parent showOrParseArgs)
                        ++
557
558
559
560
                        liftOptions get2 set2
                        (Cabal.buildOptions progConf showOrParseArgs)
                        ++
                        liftOptions get3 set3 (buildExOptions showOrParseArgs)
561
562
  }
  where
563
564
565
    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)
566

567
568
    parent   = Cabal.testCommand
    progConf = defaultProgramConfiguration
569
570
571
572
573

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

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

592
593
    parent   = Cabal.benchmarkCommand
    progConf = defaultProgramConfiguration
ttuegel's avatar
ttuegel committed
594

595
-- ------------------------------------------------------------
596
-- * Fetch command
597
-- ------------------------------------------------------------
598

599
600
601
602
data FetchFlags = FetchFlags {
--    fetchOutput    :: Flag FilePath,
      fetchDeps      :: Flag Bool,
      fetchDryRun    :: Flag Bool,
603
      fetchSolver           :: Flag PreSolver,
604
605
606
      fetchMaxBackjumps     :: Flag Int,
      fetchReorderGoals     :: Flag Bool,
      fetchIndependentGoals :: Flag Bool,
607
      fetchShadowPkgs       :: Flag Bool,
Andres Löh's avatar
Andres Löh committed
608
      fetchStrongFlags      :: Flag Bool,
609
610
611
612
613
614
615
616
      fetchVerbosity :: Flag Verbosity
    }

defaultFetchFlags :: FetchFlags
defaultFetchFlags = FetchFlags {
--  fetchOutput    = mempty,
    fetchDeps      = toFlag True,
    fetchDryRun    = toFlag False,
617
618
    fetchSolver           = Flag defaultSolver,
    fetchMaxBackjumps     = Flag defaultMaxBackjumps,
619
    fetchReorderGoals     = Flag False,
620
    fetchIndependentGoals = Flag False,
621
    fetchShadowPkgs       = Flag False,
Andres Löh's avatar
Andres Löh committed
622
    fetchStrongFlags      = Flag False,
623
624
625
626
    fetchVerbosity = toFlag normal
   }

fetchCommand :: CommandUI FetchFlags
Duncan Coutts's avatar
Duncan Coutts committed
627
628
fetchCommand = CommandUI {
    commandName         = "fetch",
629
    commandSynopsis     = "Downloads packages for later installation.",
630
631
632
633
634
    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",
635
    commandNotes        = Nothing,
636
    commandDefaultFlags = defaultFetchFlags,
637
    commandOptions      = \ showOrParseArgs -> [
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
         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
659
660
661
662

       ] ++

       optionSolver      fetchSolver           (\v flags -> flags { fetchSolver           = v }) :
663
664
       optionSolverFlags showOrParseArgs
                         fetchMaxBackjumps     (\v flags -> flags { fetchMaxBackjumps     = v })
665
666
                         fetchReorderGoals     (\v flags -> flags { fetchReorderGoals     = v })
                         fetchIndependentGoals (\v flags -> flags { fetchIndependentGoals = v })
667
                         fetchShadowPkgs       (\v flags -> flags { fetchShadowPkgs       = v })
Andres Löh's avatar
Andres Löh committed
668
                         fetchStrongFlags      (\v flags -> flags { fetchStrongFlags      = v })
669

Duncan Coutts's avatar
Duncan Coutts committed
670
671
  }

672
673
674
675
676
677
-- ------------------------------------------------------------
-- * Freeze command
-- ------------------------------------------------------------

data FreezeFlags = FreezeFlags {
      freezeDryRun           :: Flag Bool,
678
679
      freezeTests            :: Flag Bool,
      freezeBenchmarks       :: Flag Bool,
680
681
682
683
684
      freezeSolver           :: Flag PreSolver,
      freezeMaxBackjumps     :: Flag Int,
      freezeReorderGoals     :: Flag Bool,
      freezeIndependentGoals :: Flag Bool,
      freezeShadowPkgs       :: Flag Bool,
Andres Löh's avatar
Andres Löh committed
685
      freezeStrongFlags      :: Flag Bool,
686
687
688
689
690
691
      freezeVerbosity        :: Flag Verbosity
    }

defaultFreezeFlags :: FreezeFlags
defaultFreezeFlags = FreezeFlags {
    freezeDryRun           = toFlag False,
692
693
    freezeTests            = toFlag False,
    freezeBenchmarks       = toFlag False,
694
695
    freezeSolver           = Flag defaultSolver,
    freezeMaxBackjumps     = Flag defaultMaxBackjumps,
696
    freezeReorderGoals     = Flag False,
697
698
    freezeIndependentGoals = Flag False,
    freezeShadowPkgs       = Flag False,
Andres Löh's avatar
Andres Löh committed
699
    freezeStrongFlags      = Flag False,
700
701
702
703
704
705
706
    freezeVerbosity        = toFlag normal
   }

freezeCommand :: CommandUI FreezeFlags
freezeCommand = CommandUI {
    commandName         = "freeze",
    commandSynopsis     = "Freeze dependencies.",
707
708
709
710
711
712
713
714
    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",
715
    commandNotes        = Nothing,
716
    commandUsage        = usageFlags "freeze",
717
718
719
720
721
722
723
724
725
    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

726
727
728
729
730
731
732
733
734
735
       , 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 [] [])

736
737
738
739
740
741
742
743
       ] ++

       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
744
                         freezeStrongFlags      (\v flags -> flags { freezeStrongFlags      = v })
745
746
747

  }

748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
genBoundsCommand :: CommandUI FreezeFlags
genBoundsCommand = CommandUI {
    commandName         = "gen-bounds",
    commandSynopsis     = "Generate dependency bounds.",
    commandDescription  = Just $ \_ -> wrapText $
         "Generates bounds for all dependencies that do not currently have them. "
      ++ "Generated bounds are printed to stdout.  You can then paste them into your .cabal file.\n"
      ++ "\n",
    commandNotes        = Nothing,
    commandUsage        = usageFlags "gen-bounds",
    commandDefaultFlags = defaultFreezeFlags,
    commandOptions      = \ _ -> [
     optionVerbosity freezeVerbosity (\v flags -> flags { freezeVerbosity = v })
     ]
  }

764
765
766
767
-- ------------------------------------------------------------
-- * Other commands
-- ------------------------------------------------------------

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

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

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

804
805
806
checkCommand  :: CommandUI (Flag Verbosity)
checkCommand = CommandUI {
    commandName         = "check",
807
    commandSynopsis     = "Check the package for common mistakes.",
808
809
810
811
812
813
    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",
814
    commandNotes        = Nothing,
815
    commandUsage        = \pname -> "Usage: " ++ pname ++ " check\n",
816
    commandDefaultFlags = toFlag normal,
817
    commandOptions      = \_ -> []
818
819
  }

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

831
832
833
834
835
836
837
838
839
840
841
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      = \_ -> []
  }

Maciek Makowski's avatar
Maciek Makowski committed
842
843
844
845
846
847
848
849
850
851
852
853
manpageCommand :: CommandUI (Flag Verbosity)
manpageCommand = CommandUI {
    commandName         = "manpage",
    commandSynopsis     = "Outputs manpage source.",
    commandDescription  = Just $ \_ ->
      "Output manpage source to STDOUT.\n",
    commandNotes        = Nothing,
    commandUsage        = usageFlags "manpage",
    commandDefaultFlags = toFlag normal,
    commandOptions      = \_ -> [optionVerbosity id const]
  }

854
runCommand :: CommandUI (BuildFlags, BuildExFlags)
refold's avatar
refold committed
855
856
runCommand = CommandUI {
    commandName         = "run",
857
    commandSynopsis     = "Builds and runs an executable.",
858
    commandDescription  = Just $ \pname -> wrapText $
859
860
         "Builds and then runs the specified executable. If no executable is "
      ++ "specified, but the package contains just one executable, that one "
861
862
863
864
      ++ "is built and executed.\n"
      ++ "\n"
      ++ "Use `" ++ pname ++ " test --show-details=streaming` to run a "
      ++ "test-suite and get its full output.\n",
865
866
867
868
    commandNotes        = Just $ \pname ->
          "Examples:\n"
       ++ "  " ++ pname ++ " run\n"
       ++ "    Run the only executable in the current package;\n"
869
870
       ++ "  " ++ pname ++ " run foo -- --fooflag\n"
       ++ "    Works similar to `./foo --fooflag`.\n",
871
872
    commandUsage        = usageAlternatives "run"
        ["[FLAGS] [EXECUTABLE] [-- EXECUTABLE_FLAGS]"],
refold's avatar
refold committed
873
    commandDefaultFlags = mempty,
874
875
    commandOptions      =
      \showOrParseArgs -> liftOptions fst setFst
876
                          (commandOptions parent showOrParseArgs)
877
878
879
                          ++
                          liftOptions snd setSnd
                          (buildExOptions showOrParseArgs)
refold's avatar
refold committed
880
881
  }
  where
882
883
884
    setFst a (_,b) = (a,b)
    setSnd b (a,_) = (a,b)

885
    parent = Cabal.buildCommand defaultProgramConfiguration
refold's avatar
refold committed
886

887
888
889
890
891
892
893
894
-- ------------------------------------------------------------
-- * Report flags
-- ------------------------------------------------------------

data ReportFlags = ReportFlags {
    reportUsername  :: Flag Username,
    reportPassword  :: Flag Password,
    reportVerbosity :: Flag Verbosity
895
  } deriving Generic
896
897
898
899
900
901
902
903
904

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

reportCommand :: CommandUI ReportFlags
905
906
907
reportCommand = CommandUI {
    commandName         = "report",
    commandSynopsis     = "Upload build reports to a remote server.",
908
909
    commandDescription  = Nothing,
    commandNotes        = Just $ \_ ->
910
         "You can store your Hackage login in the ~/.cabal/config file\n",
911
    commandUsage        = usageAlternatives "report" ["[FLAGS]"],
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
    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))
      ]
928
929
  }

930
instance Monoid ReportFlags where
931
  mempty = gmempty
932
933
934
  mappend = (<>)

instance Semigroup ReportFlags where
935
  (<>) = gmappend
936

937
-- ------------------------------------------------------------
938
-- * Get flags
939
940
-- ------------------------------------------------------------

941
942
943
944
945
data GetFlags = GetFlags {
    getDestDir          :: Flag FilePath,
    getPristine         :: Flag Bool,
    getSourceRepository :: Flag (Maybe RepoKind),
    getVerbosity        :: Flag Verbosity
946
  } deriving Generic
947

948
949
950
951
952
953
defaultGetFlags :: GetFlags
defaultGetFlags = GetFlags {
    getDestDir          = mempty,
    getPristine         = mempty,
    getSourceRepository = mempty,
    getVerbosity        = toFlag normal
954
955
   }

956
957
958
getCommand :: CommandUI GetFlags
getCommand = CommandUI {
    commandName         = "get",
959
960
    commandSynopsis     = "Download/Extract a package's source code (repository).",
    commandDescription  = Just $ \_ -> wrapText $
961
962
963
964
          "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",
965
966
967
968
    commandNotes        = Just $ \pname ->
          "Examples:\n"
       ++ "  " ++ pname ++ " get hlint\n"
       ++ "    Download the latest stable version of hlint;\n"
969
       ++ "  " ++ pname ++ " get lens --source-repository=head\n"
970
       ++ "    Download the source repository (i.e. git clone from github).\n",
971
    commandUsage        = usagePackages "get",
972
    commandDefaultFlags = defaultGetFlags,
973
    commandOptions      = \_ -> [
974
        optionVerbosity getVerbosity (\v flags -> flags { getVerbosity = v })
975
976

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

981
       ,option "s" ["source-repository"]
982
         "Copy the package's source repository (ie git clone, darcs get, etc as appropriate)."
983
984
985
986
987
988
         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))

989
990
991
       , option [] ["pristine"]
           ("Unpack the original pristine tarball, rather than updating the "
           ++ ".cabal file with the latest revision from the package archive.")
992
           getPristine (\v flags -> flags { getPristine = v })
993
           trueArg
994
995
996
       ]
  }

997
998
999
1000
-- 'cabal unpack' is a deprecated alias for 'cabal get'.
unpackCommand :: CommandUI GetFlags
unpackCommand = getCommand {
  commandName  = "unpack",