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

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

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

69

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

107
108
import Data.Char
         ( isSpace, isAlphaNum )
109
import Data.List
110
         ( intercalate, deleteFirstsBy )
111
import Data.Maybe
112
         ( listToMaybe, maybeToList, fromMaybe )
113
#if !MIN_VERSION_base(4,8,0)
114
115
import Data.Monoid
         ( Monoid(..) )
116
#endif
117
118
import GHC.Generics (Generic)
import Distribution.Compat.Binary (Binary)
119
120
121
122
123
124
import Control.Monad
         ( liftM )
import System.FilePath
         ( (</>) )
import Network.URI
         ( parseAbsoluteURI, uriToString )
125

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

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

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

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

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

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

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

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

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

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

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

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

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

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

349
filterConfigureFlags :: ConfigFlags -> Version -> ConfigFlags
350
filterConfigureFlags flags cabalLibVersion
351
  | cabalLibVersion >= Version [1,23,0] [] = flags_latest
352
  -- ^ NB: we expect the latest version to be the most common case.
353
354
355
  | 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
356
  | cabalLibVersion <  Version [1,18,0] [] = flags_1_18_0
357
  | cabalLibVersion <  Version [1,19,1] [] = flags_1_19_0
358
  | cabalLibVersion <  Version [1,19,2] [] = flags_1_19_1
359
  | cabalLibVersion <  Version [1,21,1] [] = flags_1_20_0
360
  | cabalLibVersion <  Version [1,22,0] [] = flags_1_21_0
361
  | cabalLibVersion <  Version [1,23,0] [] = flags_1_22_0
362
  | otherwise = flags_latest
363
  where
364
    -- Cabal >= 1.19.1 uses '--dependency' and does not need '--constraint'.
365
366
    flags_latest = flags        { configConstraints = [] }

367
368
    -- Cabal < 1.23 doesn't know about '--profiling-detail'.
    flags_1_22_0 = flags_latest { configProfDetail    = NoFlag
369
370
                                , configProfLibDetail = NoFlag
                                , configIPID          = NoFlag }
371

372
    -- Cabal < 1.22 doesn't know about '--disable-debug-info'.
373
    flags_1_21_0 = flags_1_22_0 { configDebugInfo = NoFlag }
374

375
    -- Cabal < 1.21.1 doesn't know about 'disable-relocatable'
376
377
    -- Cabal < 1.21.1 doesn't know about 'enable-profiling'
    flags_1_20_0 =
378
      flags_1_21_0 { configRelocatable = NoFlag
379
380
381
382
                   , configProf = NoFlag
                   , configProfExe = configProf flags
                   , configProfLib =
                     mappend (configProf flags) (configProfLib flags)
383
384
                   , configCoverage = NoFlag
                   , configLibCoverage = configCoverage flags
385
                   }
386
387
388
389
    -- 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 }
390
391
392
    -- Cabal < 1.19.1 uses '--constraint' instead of '--dependency'.
    flags_1_19_0 = flags_1_19_1 { configDependencies = []
                                , configConstraints  = configConstraints flags }
393
    -- Cabal < 1.18.0 doesn't know about --extra-prog-path and --sysconfdir.
394
    flags_1_18_0 = flags_1_19_0 { configProgramPathExtra = toNubList []
395
396
                                , configInstallDirs = configInstallDirs_1_18_0}
    configInstallDirs_1_18_0 = (configInstallDirs flags) { sysconfdir = NoFlag }
397
    -- Cabal < 1.14.0 doesn't know about '--disable-benchmarks'.
398
    flags_1_14_0 = flags_1_18_0 { configBenchmarks  = NoFlag }
399
    -- Cabal < 1.10.0 doesn't know about '--disable-tests'.
400
    flags_1_10_0 = flags_1_14_0 { configTests       = NoFlag }
401
    -- Cabal < 1.3.10 does not grok the '--constraints' flag.
402
    flags_1_3_10 = flags_1_10_0 { configConstraints = [] }
403

404
405
406
407
408
409
410
411
-- ------------------------------------------------------------
-- * Config extra flags
-- ------------------------------------------------------------

-- | cabal configure takes some extra flags beyond runghc Setup configure
--
data ConfigExFlags = ConfigExFlags {
    configCabalVersion :: Flag Version,
412
    configExConstraints:: [(UserConstraint, ConstraintSource)],
413
    configPreferences  :: [Dependency],
414
415
    configSolver       :: Flag PreSolver,
    configAllowNewer   :: Flag AllowNewer
416
  }
417
  deriving (Eq, Generic)
418
419

defaultConfigExFlags :: ConfigExFlags
420
421
defaultConfigExFlags = mempty { configSolver     = Flag defaultSolver
                              , configAllowNewer = Flag AllowNewerNone }
422
423
424
425
426

configureExCommand :: CommandUI (ConfigFlags, ConfigExFlags)
configureExCommand = configureCommand {
    commandDefaultFlags = (mempty, defaultConfigExFlags),
    commandOptions      = \showOrParseArgs ->
427
         liftOptions fst setFst
428
         (filter ((`notElem` ["constraint", "dependency", "exact-configuration"])
429
                  . optionName) $ configureOptions  showOrParseArgs)
430
431
      ++ liftOptions snd setSnd
         (configureExOptions showOrParseArgs ConstraintSourceCommandlineFlag)
432
433
434
435
436
  }
  where
    setFst a (_,b) = (a,b)
    setSnd b (a,_) = (a,b)

437
438
439
440
configureExOptions :: ShowOrParseArgs
                   -> ConstraintSource
                   -> [OptionField ConfigExFlags]
configureExOptions _showOrParseArgs src =
441
442
443
444
445
446
447
  [ 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))
448
449
450
451
  , option [] ["constraint"]
      "Specify constraints on a package (version, installed/source, flags)"
      configExConstraints (\v flags -> flags { configExConstraints = v })
      (reqArg "CONSTRAINT"
452
453
              ((\x -> [(x, src)]) `fmap` ReadE readUserConstraint)
              (map $ display . fst))
454
455
456
457

  , option [] ["preference"]
      "Specify preferences (soft constraints) on the version of a package"
      configPreferences (\v flags -> flags { configPreferences = v })
458
459
460
461
      (reqArg "CONSTRAINT"
              (readP_to_E (const "dependency expected")
                          (fmap (\x -> [x]) parse))
              (map display))
462
463

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

  , option [] ["allow-newer"]
cheecheeo's avatar
cheecheeo committed
466
    ("Ignore upper bounds in all dependencies or " ++ allowNewerArgument)
467
    configAllowNewer (\v flags -> flags { configAllowNewer = v})
cheecheeo's avatar
cheecheeo committed
468
    (optArg allowNewerArgument
469
470
471
     (fmap Flag allowNewerParser) (Flag AllowNewerAll)
     allowNewerPrinter)

472
  ]
cheecheeo's avatar
cheecheeo committed
473
  where allowNewerArgument = "DEPS"
474
475
476
477

instance Monoid ConfigExFlags where
  mempty = ConfigExFlags {
    configCabalVersion = mempty,
478
    configExConstraints= mempty,
479
    configPreferences  = mempty,
480
481
    configSolver       = mempty,
    configAllowNewer   = mempty
482
483
484
  }
  mappend a b = ConfigExFlags {
    configCabalVersion = combine configCabalVersion,
485
    configExConstraints= combine configExConstraints,
486
    configPreferences  = combine configPreferences,
487
488
    configSolver       = combine configSolver,
    configAllowNewer   = combine configAllowNewer
489
490
491
  }
    where combine field = field a `mappend` field b

ttuegel's avatar
ttuegel committed
492
493
494
495
-- ------------------------------------------------------------
-- * Build flags
-- ------------------------------------------------------------

496
497
498
499
500
501
502
503
504
505
data SkipAddSourceDepsCheck =
  SkipAddSourceDepsCheck | DontSkipAddSourceDepsCheck
  deriving Eq

data BuildExFlags = BuildExFlags {
  buildOnly     :: Flag SkipAddSourceDepsCheck
}

buildExOptions :: ShowOrParseArgs -> [OptionField BuildExFlags]
buildExOptions _showOrParseArgs =
506
  option [] ["only"]
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
  "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

-- ------------------------------------------------------------
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
-- * 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

556
557
558
559
-- ------------------------------------------------------------
-- * Test command
-- ------------------------------------------------------------

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

578
579
    parent   = Cabal.testCommand
    progConf = defaultProgramConfiguration
580
581
582
583
584

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

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

603
604
    parent   = Cabal.benchmarkCommand
    progConf = defaultProgramConfiguration
ttuegel's avatar
ttuegel committed
605

606
-- ------------------------------------------------------------
607
-- * Fetch command
608
-- ------------------------------------------------------------
609

610
611
612
613
data FetchFlags = FetchFlags {
--    fetchOutput    :: Flag FilePath,
      fetchDeps      :: Flag Bool,
      fetchDryRun    :: Flag Bool,
614
      fetchSolver           :: Flag PreSolver,
615
616
617
      fetchMaxBackjumps     :: Flag Int,
      fetchReorderGoals     :: Flag Bool,
      fetchIndependentGoals :: Flag Bool,
618
      fetchShadowPkgs       :: Flag Bool,
Andres Löh's avatar
Andres Löh committed
619
      fetchStrongFlags      :: Flag Bool,
620
621
622
623
624
625
626
627
      fetchVerbosity :: Flag Verbosity
    }

defaultFetchFlags :: FetchFlags
defaultFetchFlags = FetchFlags {
--  fetchOutput    = mempty,
    fetchDeps      = toFlag True,
    fetchDryRun    = toFlag False,
628
629
    fetchSolver           = Flag defaultSolver,
    fetchMaxBackjumps     = Flag defaultMaxBackjumps,
630
    fetchReorderGoals     = Flag False,
631
    fetchIndependentGoals = Flag False,
632
    fetchShadowPkgs       = Flag False,
Andres Löh's avatar
Andres Löh committed
633
    fetchStrongFlags      = Flag False,
634
635
636
637
    fetchVerbosity = toFlag normal
   }

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

       ] ++

       optionSolver      fetchSolver           (\v flags -> flags { fetchSolver           = v }) :
674
675
       optionSolverFlags showOrParseArgs
                         fetchMaxBackjumps     (\v flags -> flags { fetchMaxBackjumps     = v })
676
677
                         fetchReorderGoals     (\v flags -> flags { fetchReorderGoals     = v })
                         fetchIndependentGoals (\v flags -> flags { fetchIndependentGoals = v })
678
                         fetchShadowPkgs       (\v flags -> flags { fetchShadowPkgs       = v })
Andres Löh's avatar
Andres Löh committed
679
                         fetchStrongFlags      (\v flags -> flags { fetchStrongFlags      = v })
680

Duncan Coutts's avatar
Duncan Coutts committed
681
682
  }

683
684
685
686
687
688
-- ------------------------------------------------------------
-- * Freeze command
-- ------------------------------------------------------------

data FreezeFlags = FreezeFlags {
      freezeDryRun           :: Flag Bool,
689
690
      freezeTests            :: Flag Bool,
      freezeBenchmarks       :: Flag Bool,
691
692
693
694
695
      freezeSolver           :: Flag PreSolver,
      freezeMaxBackjumps     :: Flag Int,
      freezeReorderGoals     :: Flag Bool,
      freezeIndependentGoals :: Flag Bool,
      freezeShadowPkgs       :: Flag Bool,
Andres Löh's avatar
Andres Löh committed
696
      freezeStrongFlags      :: Flag Bool,
697
698
699
700
701
702
      freezeVerbosity        :: Flag Verbosity
    }

defaultFreezeFlags :: FreezeFlags
defaultFreezeFlags = FreezeFlags {
    freezeDryRun           = toFlag False,
703
704
    freezeTests            = toFlag False,
    freezeBenchmarks       = toFlag False,
705
706
    freezeSolver           = Flag defaultSolver,
    freezeMaxBackjumps     = Flag defaultMaxBackjumps,
707
    freezeReorderGoals     = Flag False,
708
709
    freezeIndependentGoals = Flag False,
    freezeShadowPkgs       = Flag False,
Andres Löh's avatar
Andres Löh committed
710
    freezeStrongFlags      = Flag False,
711
712
713
714
715
716
717
    freezeVerbosity        = toFlag normal
   }

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

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

747
748
749
750
751
752
753
754
       ] ++

       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
755
                         freezeStrongFlags      (\v flags -> flags { freezeStrongFlags      = v })
756
757
758

  }

759
760
761
762
-- ------------------------------------------------------------
-- * Other commands
-- ------------------------------------------------------------

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

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

Duncan Coutts's avatar
Duncan Coutts committed
788
789
790
791
792
793
794
795
796
797
798
{-
cleanCommand  :: CommandUI ()
cleanCommand = makeCommand name shortDesc longDesc emptyFlags options
  where
    name       = "clean"
    shortDesc  = "Removes downloaded files"
    longDesc   = Nothing
    emptyFlags = ()
    options _  = []
-}

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

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

826
827
828
829
830
831
832
833
834
835
836
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
837
838
839
840
841
842
843
844
845
846
847
848
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]
  }

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

880
    parent = Cabal.buildCommand defaultProgramConfiguration
refold's avatar
refold committed
881

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

925
926
927
928
929
930
931
932
933
934
935
936
937
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

938
-- ------------------------------------------------------------
939
-- * Get flags
940
941
-- ------------------------------------------------------------

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

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

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

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

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

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

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