Setup.hs 86.8 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(..), IsCandidate(..)
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
58
         ( Username(..), Password(..), RemoteRepo(..) )
59
60
import Distribution.Client.BuildReports.Types
         ( ReportLevel(..) )
61
import Distribution.Client.Dependency.Types
62
         ( PreSolver(..) )
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
import Distribution.Solver.Types.ConstraintSource
71
import Distribution.Solver.Types.Settings
72

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

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

128
129
globalCommand :: [Command action] -> CommandUI GlobalFlags
globalCommand commands = CommandUI {
130
    commandName         = "",
131
132
    commandSynopsis     =
         "Command line interface to the Haskell Cabal infrastructure.",
133
134
135
136
    commandUsage        = \pname ->
         "See http://www.haskell.org/cabal/ for more information.\n"
      ++ "\n"
      ++ "Usage: " ++ pname ++ " [GLOBAL FLAGS] [COMMAND [FLAGS]]\n",
137
    commandDescription  = Just $ \pname ->
138
139
140
      let
        commands' = commands ++ [commandAddAction helpCommandUI undefined]
        cmdDescs = getNormalCommandDescriptions commands'
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
166
167
168
        -- 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"
169
          , "gen-bounds"
170
171
172
173
174
175
176
          , "haddock"
          , "hscolour"
          , "copy"
          , "register"
          , "sandbox"
          , "exec"
          ]
177
178
        maxlen    = maximum $ [length name | (name, _) <- cmdDescs]
        align str = str ++ replicate (maxlen - length str) ' '
179
180
181
182
183
184
185
186
187
        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
188
189
      in
         "Commands:\n"
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
217
218
219
      ++ 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"
220
        , addCmd "gen-bounds"
221
222
223
224
225
226
        , addCmd "haddock"
        , addCmd "hscolour"
        , addCmd "copy"
        , addCmd "register"
        , par
        , startGroup "sandbox"
227
        , addCmd "sandbox"
228
229
230
231
232
        , addCmd "exec"
        , addCmdCustom "repl" "Open interpreter with access to sandbox packages."
        ] ++ if null otherCmds then [] else par
                                           :startGroup "other"
                                           :[addCmd n | n <- otherCmds])
233
234
      ++ "\n"
      ++ "For more information about a command use:\n"
235
236
      ++ "   " ++ pname ++ " COMMAND --help\n"
      ++ "or " ++ pname ++ " help COMMAND\n"
237
      ++ "\n"
238
      ++ "To install Cabal packages from hackage use:\n"
239
240
      ++ "  " ++ pname ++ " install foo [--dry-run]\n"
      ++ "\n"
241
242
      ++ "Occasionally you need to update the list of available packages:\n"
      ++ "  " ++ pname ++ " update\n",
243
    commandNotes = Nothing,
244
    commandDefaultFlags = mempty,
245
246
247
248
249
250
251
252
253
254
255
    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"]
256
257
258
259
260
261
262
263
264
265
266
267
268
269
         "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")

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

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

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

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

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

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

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

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

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

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

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

334
configureCommand :: CommandUI ConfigFlags
335
336
configureCommand = c
  { commandDefaultFlags = mempty
337
338
339
  , commandNotes = Just $ \pname -> (case commandNotes c of
         Nothing -> ""
         Just n  -> n pname ++ "\n")
340
341
342
343
344
345
       ++ "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
346
  }
347
348
 where
  c = Cabal.configureCommand defaultProgramConfiguration
Duncan Coutts's avatar
Duncan Coutts committed
349

350
351
352
configureOptions ::  ShowOrParseArgs -> [OptionField ConfigFlags]
configureOptions = commandOptions configureCommand

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

378
379
    -- Cabal < 1.23 doesn't know about '--profiling-detail'.
    flags_1_22_0 = flags_latest { configProfDetail    = NoFlag
380
381
                                , configProfLibDetail = NoFlag
                                , configIPID          = NoFlag }
382

383
    -- Cabal < 1.22 doesn't know about '--disable-debug-info'.
384
    flags_1_21_0 = flags_1_22_0 { configDebugInfo = NoFlag }
385

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

419
420
421
422
423
424
425
426
-- ------------------------------------------------------------
-- * Config extra flags
-- ------------------------------------------------------------

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

defaultConfigExFlags :: ConfigExFlags
434
defaultConfigExFlags = mempty { configSolver     = Flag defaultSolver }
435
436
437
438
439

configureExCommand :: CommandUI (ConfigFlags, ConfigExFlags)
configureExCommand = configureCommand {
    commandDefaultFlags = (mempty, defaultConfigExFlags),
    commandOptions      = \showOrParseArgs ->
440
         liftOptions fst setFst
441
         (filter ((`notElem` ["constraint", "dependency", "exact-configuration"])
442
                  . optionName) $ configureOptions  showOrParseArgs)
443
444
      ++ liftOptions snd setSnd
         (configureExOptions showOrParseArgs ConstraintSourceCommandlineFlag)
445
446
447
448
449
  }
  where
    setFst a (_,b) = (a,b)
    setSnd b (a,_) = (a,b)

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

instance Monoid ConfigExFlags where
481
  mempty = gmempty
482
483
484
  mappend = (<>)

instance Semigroup ConfigExFlags where
485
  (<>) = gmappend
486

ttuegel's avatar
ttuegel committed
487
488
489
490
-- ------------------------------------------------------------
-- * Build flags
-- ------------------------------------------------------------

491
492
493
494
495
496
data SkipAddSourceDepsCheck =
  SkipAddSourceDepsCheck | DontSkipAddSourceDepsCheck
  deriving Eq

data BuildExFlags = BuildExFlags {
  buildOnly     :: Flag SkipAddSourceDepsCheck
497
} deriving Generic
498
499
500

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

instance Semigroup BuildExFlags where
528
  (<>) = gmappend
529
530

-- ------------------------------------------------------------
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
-- * 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

549
550
551
552
-- ------------------------------------------------------------
-- * Test command
-- ------------------------------------------------------------

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

571
572
    parent   = Cabal.testCommand
    progConf = defaultProgramConfiguration
573
574
575
576
577

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

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

596
597
    parent   = Cabal.benchmarkCommand
    progConf = defaultProgramConfiguration
ttuegel's avatar
ttuegel committed
598

599
-- ------------------------------------------------------------
600
-- * Fetch command
601
-- ------------------------------------------------------------
602

603
604
605
606
data FetchFlags = FetchFlags {
--    fetchOutput    :: Flag FilePath,
      fetchDeps      :: Flag Bool,
      fetchDryRun    :: Flag Bool,
607
      fetchSolver           :: Flag PreSolver,
608
      fetchMaxBackjumps     :: Flag Int,
609
      fetchReorderGoals     :: Flag ReorderGoals,
610
      fetchCountConflicts   :: Flag CountConflicts,
611
612
613
      fetchIndependentGoals :: Flag IndependentGoals,
      fetchShadowPkgs       :: Flag ShadowPkgs,
      fetchStrongFlags      :: Flag StrongFlags,
614
615
616
617
618
619
620
621
      fetchVerbosity :: Flag Verbosity
    }

defaultFetchFlags :: FetchFlags
defaultFetchFlags = FetchFlags {
--  fetchOutput    = mempty,
    fetchDeps      = toFlag True,
    fetchDryRun    = toFlag False,
622
623
    fetchSolver           = Flag defaultSolver,
    fetchMaxBackjumps     = Flag defaultMaxBackjumps,
624
    fetchReorderGoals     = Flag (ReorderGoals False),
625
    fetchCountConflicts   = Flag (CountConflicts True),
626
627
628
    fetchIndependentGoals = Flag (IndependentGoals False),
    fetchShadowPkgs       = Flag (ShadowPkgs False),
    fetchStrongFlags      = Flag (StrongFlags False),
629
630
631
632
    fetchVerbosity = toFlag normal
   }

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

       ] ++

       optionSolver      fetchSolver           (\v flags -> flags { fetchSolver           = v }) :
669
670
       optionSolverFlags showOrParseArgs
                         fetchMaxBackjumps     (\v flags -> flags { fetchMaxBackjumps     = v })
671
                         fetchReorderGoals     (\v flags -> flags { fetchReorderGoals     = v })
672
                         fetchCountConflicts   (\v flags -> flags { fetchCountConflicts   = v })
673
                         fetchIndependentGoals (\v flags -> flags { fetchIndependentGoals = v })
674
                         fetchShadowPkgs       (\v flags -> flags { fetchShadowPkgs       = v })
Andres Löh's avatar
Andres Löh committed
675
                         fetchStrongFlags      (\v flags -> flags { fetchStrongFlags      = v })
676

Duncan Coutts's avatar
Duncan Coutts committed
677
678
  }

679
680
681
682
683
684
-- ------------------------------------------------------------
-- * Freeze command
-- ------------------------------------------------------------

data FreezeFlags = FreezeFlags {
      freezeDryRun           :: Flag Bool,
685
686
      freezeTests            :: Flag Bool,
      freezeBenchmarks       :: Flag Bool,
687
688
      freezeSolver           :: Flag PreSolver,
      freezeMaxBackjumps     :: Flag Int,
689
      freezeReorderGoals     :: Flag ReorderGoals,
690
      freezeCountConflicts   :: Flag CountConflicts,
691
692
693
      freezeIndependentGoals :: Flag IndependentGoals,
      freezeShadowPkgs       :: Flag ShadowPkgs,
      freezeStrongFlags      :: Flag StrongFlags,
694
695
696
697
698
699
      freezeVerbosity        :: Flag Verbosity
    }

defaultFreezeFlags :: FreezeFlags
defaultFreezeFlags = FreezeFlags {
    freezeDryRun           = toFlag False,
700
701
    freezeTests            = toFlag False,
    freezeBenchmarks       = toFlag False,
702
703
    freezeSolver           = Flag defaultSolver,
    freezeMaxBackjumps     = Flag defaultMaxBackjumps,
704
    freezeReorderGoals     = Flag (ReorderGoals False),
705
    freezeCountConflicts   = Flag (CountConflicts True),
706
707
708
    freezeIndependentGoals = Flag (IndependentGoals False),
    freezeShadowPkgs       = Flag (ShadowPkgs False),
    freezeStrongFlags      = Flag (StrongFlags False),
709
710
711
712
713
714
715
    freezeVerbosity        = toFlag normal
   }

freezeCommand :: CommandUI FreezeFlags
freezeCommand = CommandUI {
    commandName         = "freeze",
    commandSynopsis     = "Freeze dependencies.",
716
717
718
719
720
721
722
723
    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",
724
    commandNotes        = Nothing,
725
    commandUsage        = usageFlags "freeze",
726
727
728
729
730
731
732
733
734
    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

735
736
737
738
739
740
741
742
743
744
       , 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 [] [])

745
746
747
748
749
750
       ] ++

       optionSolver      freezeSolver           (\v flags -> flags { freezeSolver           = v }) :
       optionSolverFlags showOrParseArgs
                         freezeMaxBackjumps     (\v flags -> flags { freezeMaxBackjumps     = v })
                         freezeReorderGoals     (\v flags -> flags { freezeReorderGoals     = v })
751
                         freezeCountConflicts   (\v flags -> flags { freezeCountConflicts   = v })
752
753
                         freezeIndependentGoals (\v flags -> flags { freezeIndependentGoals = v })
                         freezeShadowPkgs       (\v flags -> flags { freezeShadowPkgs       = v })
Andres Löh's avatar
Andres Löh committed
754
                         freezeStrongFlags      (\v flags -> flags { freezeStrongFlags      = v })
755
756
757

  }

758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
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 })
     ]
  }

774
775
776
777
-- ------------------------------------------------------------
-- * Other commands
-- ------------------------------------------------------------

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

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

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

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

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

841
842
843
844
845
846
847
848
849
850
851
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
852
853
854
855
856
857
858
859
860
861
862
863
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]
  }

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

895
    parent = Cabal.buildCommand defaultProgramConfiguration
refold's avatar
refold committed
896

897
898
899
900
901
902
903
904
-- ------------------------------------------------------------
-- * Report flags
-- ------------------------------------------------------------

data ReportFlags = ReportFlags {
    reportUsername  :: Flag Username,
    reportPassword  :: Flag Password,
    reportVerbosity :: Flag Verbosity
905
  } deriving Generic
906
907
908
909
910
911
912
913
914

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

reportCommand :: CommandUI ReportFlags
915
916
917
reportCommand = CommandUI {
    commandName         = "report",
    commandSynopsis     = "Upload build reports to a remote server.",
918
919
    commandDescription  = Nothing,
    commandNotes        = Just $ \_ ->
920
         "You can store your Hackage login in the ~/.cabal/config file\n",
921
    commandUsage        = usageAlternatives "report" ["[FLAGS]"],
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
    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))
      ]
938
939
  }

940
instance Monoid ReportFlags where
941
  mempty = gmempty
942
943
944
  mappend = (<>)

instance Semigroup ReportFlags where
945
  (<>) = gmappend
946

947
-- ------------------------------------------------------------
948
-- * Get flags
949
950
-- ------------------------------------------------------------

951
952
953
954
955
data GetFlags = GetFlags {
    getDestDir          :: Flag FilePath,
    getPristine         :: Flag Bool,
    getSourceRepository :: Flag (Maybe RepoKind),
    getVerbosity        :: Flag Verbosity
956
  } deriving Generic
957

958
959
960
961
962
963
defaultGetFlags :: GetFlags
defaultGetFlags = GetFlags {
    getDestDir          = mempty,
    getPristine         = mempty,
    getSourceRepository = mempty,
    getVerbosity        = toFlag normal
964
965
   }

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

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