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

    , parsePackageArgs
45
46
47
    --TODO: stop exporting these:
    , showRepo
    , parseRepo
48
    , readRepo
49
50
    ) where

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

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

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

114
115
116
117
118
119
-- ------------------------------------------------------------
-- * Global flags
-- ------------------------------------------------------------

-- | Flags that apply at the top level, not to any sub-command.
data GlobalFlags = GlobalFlags {
120
121
122
123
    globalVersion           :: Flag Bool,
    globalNumericVersion    :: Flag Bool,
    globalConfigFile        :: Flag FilePath,
    globalSandboxConfigFile :: Flag FilePath,
U-CIQDEV\gbazerman's avatar
U-CIQDEV\gbazerman committed
124
    globalConstraintsFile   :: Flag FilePath,
125
    globalRemoteRepos       :: NubList RemoteRepo,     -- ^ Available Hackage servers.
126
    globalCacheDir          :: Flag FilePath,
127
    globalLocalRepos        :: NubList FilePath,
128
    globalLogsDir           :: Flag FilePath,
129
    globalWorldFile         :: Flag FilePath,
130
    globalRequireSandbox    :: Flag Bool,
131
132
    globalIgnoreSandbox     :: Flag Bool,
    globalHttpTransport     :: Flag String
133
  }
Duncan Coutts's avatar
Duncan Coutts committed
134

135
136
defaultGlobalFlags :: GlobalFlags
defaultGlobalFlags  = GlobalFlags {
137
138
139
140
    globalVersion           = Flag False,
    globalNumericVersion    = Flag False,
    globalConfigFile        = mempty,
    globalSandboxConfigFile = mempty,
U-CIQDEV\gbazerman's avatar
U-CIQDEV\gbazerman committed
141
    globalConstraintsFile   = mempty,
142
    globalRemoteRepos       = mempty,
143
144
145
    globalCacheDir          = mempty,
    globalLocalRepos        = mempty,
    globalLogsDir           = mempty,
146
    globalWorldFile         = mempty,
147
    globalRequireSandbox    = Flag False,
148
149
    globalIgnoreSandbox     = Flag False,
    globalHttpTransport     = mempty
150
151
  }

152
153
globalCommand :: [Command action] -> CommandUI GlobalFlags
globalCommand commands = CommandUI {
154
    commandName         = "",
155
156
    commandSynopsis     =
         "Command line interface to the Haskell Cabal infrastructure.",
157
158
159
160
    commandUsage        = \pname ->
         "See http://www.haskell.org/cabal/ for more information.\n"
      ++ "\n"
      ++ "Usage: " ++ pname ++ " [GLOBAL FLAGS] [COMMAND [FLAGS]]\n",
161
    commandDescription  = Just $ \pname ->
162
163
164
      let
        commands' = commands ++ [commandAddAction helpCommandUI undefined]
        cmdDescs = getNormalCommandDescriptions commands'
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
        -- 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"
          ]
200
201
        maxlen    = maximum $ [length name | (name, _) <- cmdDescs]
        align str = str ++ replicate (maxlen - length str) ' '
202
203
204
205
206
207
208
209
210
        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
211
212
      in
         "Commands:\n"
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
      ++ 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"
249
        , addCmd "sandbox"
250
251
252
253
254
        , addCmd "exec"
        , addCmdCustom "repl" "Open interpreter with access to sandbox packages."
        ] ++ if null otherCmds then [] else par
                                           :startGroup "other"
                                           :[addCmd n | n <- otherCmds])
255
256
      ++ "\n"
      ++ "For more information about a command use:\n"
257
258
      ++ "   " ++ pname ++ " COMMAND --help\n"
      ++ "or " ++ pname ++ " help COMMAND\n"
259
      ++ "\n"
260
      ++ "To install Cabal packages from hackage use:\n"
261
262
      ++ "  " ++ pname ++ " install foo [--dry-run]\n"
      ++ "\n"
263
264
      ++ "Occasionally you need to update the list of available packages:\n"
      ++ "  " ++ pname ++ " update\n",
265
    commandNotes = Nothing,
266
    commandDefaultFlags = mempty,
267
    commandOptions      = \showOrParseArgs ->
U-CIQDEV\gbazerman's avatar
U-CIQDEV\gbazerman committed
268
      (case showOrParseArgs of ShowArgs -> take 8; ParseArgs -> id)
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
      [option ['V'] ["version"]
         "Print version information"
         globalVersion (\v flags -> flags { globalVersion = v })
         trueArg

      ,option [] ["numeric-version"]
         "Print just the version number"
         globalNumericVersion (\v flags -> flags { globalNumericVersion = v })
         trueArg

      ,option [] ["config-file"]
         "Set an alternate location for the config file"
         globalConfigFile (\v flags -> flags { globalConfigFile = v })
         (reqArgFlag "FILE")

284
      ,option [] ["sandbox-config-file"]
285
         "Set an alternate location for the sandbox config file (default: './cabal.sandbox.config')"
286
287
288
         globalConfigFile (\v flags -> flags { globalSandboxConfigFile = v })
         (reqArgFlag "FILE")

U-CIQDEV\gbazerman's avatar
U-CIQDEV\gbazerman committed
289
290
      ,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
291
292
293
         globalConfigFile (\v flags -> flags {globalConstraintsFile = v})
         (reqArgFlag "FILE")

294
      ,option [] ["require-sandbox"]
Mikhail Glushenkov's avatar
Mikhail Glushenkov committed
295
         "requiring the presence of a sandbox for sandbox-aware commands"
296
297
298
         globalRequireSandbox (\v flags -> flags { globalRequireSandbox = v })
         (boolOpt' ([], ["require-sandbox"]) ([], ["no-require-sandbox"]))

299
300
301
302
303
      ,option [] ["ignore-sandbox"]
         "Ignore any existing sandbox"
         globalIgnoreSandbox (\v flags -> flags { globalIgnoreSandbox = v })
         trueArg

304
      ,option [] ["http-transport"]
305
         "Set a transport for http(s) requests. Accepts 'curl', 'wget', 'powershell', and 'plain-http'. (default: 'curl')"
306
307
308
         globalConfigFile (\v flags -> flags { globalHttpTransport = v })
         (reqArgFlag "HttpTransport")

309
310
311
      ,option [] ["remote-repo"]
         "The name and url for a remote repository"
         globalRemoteRepos (\v flags -> flags { globalRemoteRepos = v })
312
         (reqArg' "NAME:URL" (toNubList . maybeToList . readRepo) (map showRepo . fromNubList))
313
314
315
316
317
318
319
320
321

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

324
325
326
327
328
      ,option [] ["logs-dir"]
         "The location to put log files"
         globalLogsDir (\v flags -> flags { globalLogsDir = v })
         (reqArgFlag "DIR")

329
330
331
332
      ,option [] ["world-file"]
         "The location of the world file"
         globalWorldFile (\v flags -> flags { globalWorldFile = v })
         (reqArgFlag "FILE")
333
334
335
336
337
      ]
  }

instance Monoid GlobalFlags where
  mempty = GlobalFlags {
338
339
340
341
    globalVersion           = mempty,
    globalNumericVersion    = mempty,
    globalConfigFile        = mempty,
    globalSandboxConfigFile = mempty,
U-CIQDEV\gbazerman's avatar
U-CIQDEV\gbazerman committed
342
    globalConstraintsFile   = mempty,
343
344
345
346
    globalRemoteRepos       = mempty,
    globalCacheDir          = mempty,
    globalLocalRepos        = mempty,
    globalLogsDir           = mempty,
347
    globalWorldFile         = mempty,
348
    globalRequireSandbox    = mempty,
349
350
    globalIgnoreSandbox     = mempty,
    globalHttpTransport     = mempty
351
352
  }
  mappend a b = GlobalFlags {
353
354
355
356
    globalVersion           = combine globalVersion,
    globalNumericVersion    = combine globalNumericVersion,
    globalConfigFile        = combine globalConfigFile,
    globalSandboxConfigFile = combine globalConfigFile,
U-CIQDEV\gbazerman's avatar
U-CIQDEV\gbazerman committed
357
    globalConstraintsFile   = combine globalConstraintsFile,
358
359
360
361
    globalRemoteRepos       = combine globalRemoteRepos,
    globalCacheDir          = combine globalCacheDir,
    globalLocalRepos        = combine globalLocalRepos,
    globalLogsDir           = combine globalLogsDir,
362
    globalWorldFile         = combine globalWorldFile,
363
    globalRequireSandbox    = combine globalRequireSandbox,
364
365
    globalIgnoreSandbox     = combine globalIgnoreSandbox,
    globalHttpTransport     = combine globalHttpTransport
Duncan Coutts's avatar
Duncan Coutts committed
366
  }
367
368
369
370
371
372
373
    where combine field = field a `mappend` field b

globalRepos :: GlobalFlags -> [Repo]
globalRepos globalFlags = remoteRepos ++ localRepos
  where
    remoteRepos =
      [ Repo (Left remote) cacheDir
374
      | remote <- fromNubList $ globalRemoteRepos globalFlags
375
376
377
378
      , let cacheDir = fromFlag (globalCacheDir globalFlags)
                   </> remoteRepoName remote ]
    localRepos =
      [ Repo (Right LocalRepo) local
379
      | local <- fromNubList $ globalLocalRepos globalFlags ]
380
381
382
383

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

385
configureCommand :: CommandUI ConfigFlags
386
387
configureCommand = c
  { commandDefaultFlags = mempty
388
389
390
  , commandNotes = Just $ \pname -> (case commandNotes c of
         Nothing -> ""
         Just n  -> n pname ++ "\n")
391
392
393
394
395
396
       ++ "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
397
  }
398
399
 where
  c = Cabal.configureCommand defaultProgramConfiguration
Duncan Coutts's avatar
Duncan Coutts committed
400

401
402
403
configureOptions ::  ShowOrParseArgs -> [OptionField ConfigFlags]
configureOptions = commandOptions configureCommand

404
filterConfigureFlags :: ConfigFlags -> Version -> ConfigFlags
405
filterConfigureFlags flags cabalLibVersion
406
  | cabalLibVersion >= Version [1,23,0] [] = flags_latest
407
  -- ^ NB: we expect the latest version to be the most common case.
408
409
410
  | 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
411
  | cabalLibVersion <  Version [1,18,0] [] = flags_1_18_0
412
  | cabalLibVersion <  Version [1,19,1] [] = flags_1_19_0
413
  | cabalLibVersion <  Version [1,19,2] [] = flags_1_19_1
414
  | cabalLibVersion <  Version [1,21,1] [] = flags_1_20_0
415
  | cabalLibVersion <  Version [1,22,0] [] = flags_1_21_0
416
  | cabalLibVersion <  Version [1,23,0] [] = flags_1_22_0
417
  | otherwise = flags_latest
418
  where
419
    -- Cabal >= 1.19.1 uses '--dependency' and does not need '--constraint'.
420
421
    flags_latest = flags        { configConstraints = [] }

422
423
    -- Cabal < 1.23 doesn't know about '--profiling-detail'.
    flags_1_22_0 = flags_latest { configProfDetail    = NoFlag
424
425
                                , configProfLibDetail = NoFlag
                                , configIPID          = NoFlag }
426

427
    -- Cabal < 1.22 doesn't know about '--disable-debug-info'.
428
    flags_1_21_0 = flags_1_22_0 { configDebugInfo = NoFlag }
429

430
    -- Cabal < 1.21.1 doesn't know about 'disable-relocatable'
431
432
    -- Cabal < 1.21.1 doesn't know about 'enable-profiling'
    flags_1_20_0 =
433
      flags_1_21_0 { configRelocatable = NoFlag
434
435
436
437
                   , configProf = NoFlag
                   , configProfExe = configProf flags
                   , configProfLib =
                     mappend (configProf flags) (configProfLib flags)
438
439
                   , configCoverage = NoFlag
                   , configLibCoverage = configCoverage flags
440
                   }
441
442
443
444
    -- 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 }
445
446
447
    -- Cabal < 1.19.1 uses '--constraint' instead of '--dependency'.
    flags_1_19_0 = flags_1_19_1 { configDependencies = []
                                , configConstraints  = configConstraints flags }
448
    -- Cabal < 1.18.0 doesn't know about --extra-prog-path and --sysconfdir.
449
    flags_1_18_0 = flags_1_19_0 { configProgramPathExtra = toNubList []
450
451
                                , configInstallDirs = configInstallDirs_1_18_0}
    configInstallDirs_1_18_0 = (configInstallDirs flags) { sysconfdir = NoFlag }
452
    -- Cabal < 1.14.0 doesn't know about '--disable-benchmarks'.
453
    flags_1_14_0 = flags_1_18_0 { configBenchmarks  = NoFlag }
454
    -- Cabal < 1.10.0 doesn't know about '--disable-tests'.
455
    flags_1_10_0 = flags_1_14_0 { configTests       = NoFlag }
456
    -- Cabal < 1.3.10 does not grok the '--constraints' flag.
457
    flags_1_3_10 = flags_1_10_0 { configConstraints = [] }
458

459
460
461
462
463
464
465
466
-- ------------------------------------------------------------
-- * Config extra flags
-- ------------------------------------------------------------

-- | cabal configure takes some extra flags beyond runghc Setup configure
--
data ConfigExFlags = ConfigExFlags {
    configCabalVersion :: Flag Version,
467
    configExConstraints:: [(UserConstraint, ConstraintSource)],
468
    configPreferences  :: [Dependency],
469
470
    configSolver       :: Flag PreSolver,
    configAllowNewer   :: Flag AllowNewer
471
472
473
  }

defaultConfigExFlags :: ConfigExFlags
474
475
defaultConfigExFlags = mempty { configSolver     = Flag defaultSolver
                              , configAllowNewer = Flag AllowNewerNone }
476
477
478
479
480

configureExCommand :: CommandUI (ConfigFlags, ConfigExFlags)
configureExCommand = configureCommand {
    commandDefaultFlags = (mempty, defaultConfigExFlags),
    commandOptions      = \showOrParseArgs ->
481
         liftOptions fst setFst
482
         (filter ((`notElem` ["constraint", "dependency", "exact-configuration"])
483
                  . optionName) $ configureOptions  showOrParseArgs)
484
485
      ++ liftOptions snd setSnd
         (configureExOptions showOrParseArgs ConstraintSourceCommandlineFlag)
486
487
488
489
490
  }
  where
    setFst a (_,b) = (a,b)
    setSnd b (a,_) = (a,b)

491
492
493
494
configureExOptions :: ShowOrParseArgs
                   -> ConstraintSource
                   -> [OptionField ConfigExFlags]
configureExOptions _showOrParseArgs src =
495
496
497
498
499
500
501
  [ 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))
502
503
504
505
  , option [] ["constraint"]
      "Specify constraints on a package (version, installed/source, flags)"
      configExConstraints (\v flags -> flags { configExConstraints = v })
      (reqArg "CONSTRAINT"
506
507
              ((\x -> [(x, src)]) `fmap` ReadE readUserConstraint)
              (map $ display . fst))
508
509
510
511

  , option [] ["preference"]
      "Specify preferences (soft constraints) on the version of a package"
      configPreferences (\v flags -> flags { configPreferences = v })
512
513
514
515
      (reqArg "CONSTRAINT"
              (readP_to_E (const "dependency expected")
                          (fmap (\x -> [x]) parse))
              (map display))
516
517

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

  , option [] ["allow-newer"]
cheecheeo's avatar
cheecheeo committed
520
    ("Ignore upper bounds in all dependencies or " ++ allowNewerArgument)
521
    configAllowNewer (\v flags -> flags { configAllowNewer = v})
cheecheeo's avatar
cheecheeo committed
522
    (optArg allowNewerArgument
523
524
525
     (fmap Flag allowNewerParser) (Flag AllowNewerAll)
     allowNewerPrinter)

526
  ]
cheecheeo's avatar
cheecheeo committed
527
  where allowNewerArgument = "DEPS"
528
529
530
531

instance Monoid ConfigExFlags where
  mempty = ConfigExFlags {
    configCabalVersion = mempty,
532
    configExConstraints= mempty,
533
    configPreferences  = mempty,
534
535
    configSolver       = mempty,
    configAllowNewer   = mempty
536
537
538
  }
  mappend a b = ConfigExFlags {
    configCabalVersion = combine configCabalVersion,
539
    configExConstraints= combine configExConstraints,
540
    configPreferences  = combine configPreferences,
541
542
    configSolver       = combine configSolver,
    configAllowNewer   = combine configAllowNewer
543
544
545
  }
    where combine field = field a `mappend` field b

ttuegel's avatar
ttuegel committed
546
547
548
549
-- ------------------------------------------------------------
-- * Build flags
-- ------------------------------------------------------------

550
551
552
553
554
555
556
557
558
559
data SkipAddSourceDepsCheck =
  SkipAddSourceDepsCheck | DontSkipAddSourceDepsCheck
  deriving Eq

data BuildExFlags = BuildExFlags {
  buildOnly     :: Flag SkipAddSourceDepsCheck
}

buildExOptions :: ShowOrParseArgs -> [OptionField BuildExFlags]
buildExOptions _showOrParseArgs =
560
  option [] ["only"]
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
  "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

-- ------------------------------------------------------------
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
-- * 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

610
611
612
613
-- ------------------------------------------------------------
-- * Test command
-- ------------------------------------------------------------

614
testCommand :: CommandUI (TestFlags, BuildFlags, BuildExFlags)
615
testCommand = parent {
616
617
  commandDefaultFlags = (commandDefaultFlags parent,
                         Cabal.defaultBuildFlags, mempty),
618
  commandOptions      =
619
    \showOrParseArgs -> liftOptions get1 set1
620
621
                        (commandOptions parent showOrParseArgs)
                        ++
622
623
624
625
                        liftOptions get2 set2
                        (Cabal.buildOptions progConf showOrParseArgs)
                        ++
                        liftOptions get3 set3 (buildExOptions showOrParseArgs)
626
627
  }
  where
628
629
630
    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)
631

632
633
    parent   = Cabal.testCommand
    progConf = defaultProgramConfiguration
634
635
636
637
638

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

639
benchmarkCommand :: CommandUI (BenchmarkFlags, BuildFlags, BuildExFlags)
640
benchmarkCommand = parent {
641
642
  commandDefaultFlags = (commandDefaultFlags parent,
                         Cabal.defaultBuildFlags, mempty),
643
  commandOptions      =
644
    \showOrParseArgs -> liftOptions get1 set1
645
646
                        (commandOptions parent showOrParseArgs)
                        ++
647
648
649
650
                        liftOptions get2 set2
                        (Cabal.buildOptions progConf showOrParseArgs)
                        ++
                        liftOptions get3 set3 (buildExOptions showOrParseArgs)
ttuegel's avatar
ttuegel committed
651
  }
652
  where
653
654
655
    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)
656

657
658
    parent   = Cabal.benchmarkCommand
    progConf = defaultProgramConfiguration
ttuegel's avatar
ttuegel committed
659

660
-- ------------------------------------------------------------
661
-- * Fetch command
662
-- ------------------------------------------------------------
663

664
665
666
667
data FetchFlags = FetchFlags {
--    fetchOutput    :: Flag FilePath,
      fetchDeps      :: Flag Bool,
      fetchDryRun    :: Flag Bool,
668
      fetchSolver           :: Flag PreSolver,
669
670
671
      fetchMaxBackjumps     :: Flag Int,
      fetchReorderGoals     :: Flag Bool,
      fetchIndependentGoals :: Flag Bool,
672
      fetchShadowPkgs       :: Flag Bool,
Andres Löh's avatar
Andres Löh committed
673
      fetchStrongFlags      :: Flag Bool,
674
675
676
677
678
679
680
681
      fetchVerbosity :: Flag Verbosity
    }

defaultFetchFlags :: FetchFlags
defaultFetchFlags = FetchFlags {
--  fetchOutput    = mempty,
    fetchDeps      = toFlag True,
    fetchDryRun    = toFlag False,
682
683
    fetchSolver           = Flag defaultSolver,
    fetchMaxBackjumps     = Flag defaultMaxBackjumps,
684
    fetchReorderGoals     = Flag False,
685
    fetchIndependentGoals = Flag False,
686
    fetchShadowPkgs       = Flag False,
Andres Löh's avatar
Andres Löh committed
687
    fetchStrongFlags      = Flag False,
688
689
690
691
    fetchVerbosity = toFlag normal
   }

fetchCommand :: CommandUI FetchFlags
Duncan Coutts's avatar
Duncan Coutts committed
692
693
fetchCommand = CommandUI {
    commandName         = "fetch",
694
    commandSynopsis     = "Downloads packages for later installation.",
695
696
697
698
699
    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",
700
    commandNotes        = Nothing,
701
    commandDefaultFlags = defaultFetchFlags,
702
    commandOptions      = \ showOrParseArgs -> [
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
         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
724
725
726
727

       ] ++

       optionSolver      fetchSolver           (\v flags -> flags { fetchSolver           = v }) :
728
729
       optionSolverFlags showOrParseArgs
                         fetchMaxBackjumps     (\v flags -> flags { fetchMaxBackjumps     = v })
730
731
                         fetchReorderGoals     (\v flags -> flags { fetchReorderGoals     = v })
                         fetchIndependentGoals (\v flags -> flags { fetchIndependentGoals = v })
732
                         fetchShadowPkgs       (\v flags -> flags { fetchShadowPkgs       = v })
Andres Löh's avatar
Andres Löh committed
733
                         fetchStrongFlags      (\v flags -> flags { fetchStrongFlags      = v })
734

Duncan Coutts's avatar
Duncan Coutts committed
735
736
  }

737
738
739
740
741
742
-- ------------------------------------------------------------
-- * Freeze command
-- ------------------------------------------------------------

data FreezeFlags = FreezeFlags {
      freezeDryRun           :: Flag Bool,
743
744
      freezeTests            :: Flag Bool,
      freezeBenchmarks       :: Flag Bool,
745
746
747
748
749
      freezeSolver           :: Flag PreSolver,
      freezeMaxBackjumps     :: Flag Int,
      freezeReorderGoals     :: Flag Bool,
      freezeIndependentGoals :: Flag Bool,
      freezeShadowPkgs       :: Flag Bool,
Andres Löh's avatar
Andres Löh committed
750
      freezeStrongFlags      :: Flag Bool,
751
752
753
754
755
756
      freezeVerbosity        :: Flag Verbosity
    }

defaultFreezeFlags :: FreezeFlags
defaultFreezeFlags = FreezeFlags {
    freezeDryRun           = toFlag False,
757
758
    freezeTests            = toFlag False,
    freezeBenchmarks       = toFlag False,
759
760
    freezeSolver           = Flag defaultSolver,
    freezeMaxBackjumps     = Flag defaultMaxBackjumps,
761
    freezeReorderGoals     = Flag False,
762
763
    freezeIndependentGoals = Flag False,
    freezeShadowPkgs       = Flag False,
Andres Löh's avatar
Andres Löh committed
764
    freezeStrongFlags      = Flag False,
765
766
767
768
769
770
771
    freezeVerbosity        = toFlag normal
   }

freezeCommand :: CommandUI FreezeFlags
freezeCommand = CommandUI {
    commandName         = "freeze",
    commandSynopsis     = "Freeze dependencies.",
772
773
774
775
776
777
778
779
    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",
780
    commandNotes        = Nothing,
781
    commandUsage        = usageFlags "freeze",
782
783
784
785
786
787
788
789
790
    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

791
792
793
794
795
796
797
798
799
800
       , 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 [] [])

801
802
803
804
805
806
807
808
       ] ++

       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
809
                         freezeStrongFlags      (\v flags -> flags { freezeStrongFlags      = v })
810
811
812

  }

813
814
815
816
-- ------------------------------------------------------------
-- * Other commands
-- ------------------------------------------------------------

817
updateCommand  :: CommandUI (Flag Verbosity)
Duncan Coutts's avatar
Duncan Coutts committed
818
819
updateCommand = CommandUI {
    commandName         = "update",
820
    commandSynopsis     = "Updates list of known packages.",
821
822
823
    commandDescription  = Just $ \_ ->
      "For all known remote repositories, download the package list.\n",
    commandNotes        = Just $ \_ ->
824
825
826
      relevantConfigValuesText ["remote-repo"
                               ,"remote-repo-cache"
                               ,"local-repo"],
refold's avatar
refold committed
827
    commandUsage        = usageFlags "update",
828
    commandDefaultFlags = toFlag normal,
829
    commandOptions      = \_ -> [optionVerbosity id const]
Duncan Coutts's avatar
Duncan Coutts committed
830
831
  }

832
upgradeCommand  :: CommandUI (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags)
833
upgradeCommand = configureCommand {
ijones's avatar
ijones committed
834
    commandName         = "upgrade",
835
    commandSynopsis     = "(command disabled, use install instead)",
ijones's avatar
ijones committed
836
    commandDescription  = Nothing,
refold's avatar
refold committed
837
    commandUsage        = usageFlagsOrPackages "upgrade",
838
    commandDefaultFlags = (mempty, mempty, mempty, mempty),
839
    commandOptions      = commandOptions installCommand
ijones's avatar
ijones committed
840
841
  }

Duncan Coutts's avatar
Duncan Coutts committed
842
843
844
845
846
847
848
849
850
851
852
{-
cleanCommand  :: CommandUI ()
cleanCommand = makeCommand name shortDesc longDesc emptyFlags options
  where
    name       = "clean"
    shortDesc  = "Removes downloaded files"
    longDesc   = Nothing
    emptyFlags = ()
    options _  = []
-}

853
854
855
checkCommand  :: CommandUI (Flag Verbosity)
checkCommand = CommandUI {
    commandName         = "check",
856
    commandSynopsis     = "Check the package for common mistakes.",
857
858
859
860
861
862
    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",
863
    commandNotes        = Nothing,
864
    commandUsage        = \pname -> "Usage: " ++ pname ++ " check\n",
865
    commandDefaultFlags = toFlag normal,
866
    commandOptions      = \_ -> []
867
868
  }

869
870
871
872
873
formatCommand  :: CommandUI (Flag Verbosity)
formatCommand = CommandUI {
    commandName         = "format",
    commandSynopsis     = "Reformat the .cabal file using the standard style.",
    commandDescription  = Nothing,
874
    commandNotes        = Nothing,
875
    commandUsage        = usageAlternatives "format" ["[FILE]"],
876
877
878
879
    commandDefaultFlags = toFlag normal,
    commandOptions      = \_ -> []
  }

880
881
882
883
884
885
886
887
888
889
890
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
891
892
893
894
895
896
897
898
899
900
901
902
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]
  }

903
runCommand :: CommandUI (BuildFlags, BuildExFlags)
refold's avatar
refold committed
904
905
runCommand = CommandUI {
    commandName         = "run",
906
    commandSynopsis     = "Builds and runs an executable.",
907
    commandDescription  = Just $ \pname -> wrapText $
908
909
         "Builds and then runs the specified executable. If no executable is "
      ++ "specified, but the package contains just one executable, that one "
910
911
912
913
      ++ "is built and executed.\n"
      ++ "\n"
      ++ "Use `" ++ pname ++ " test --show-details=streaming` to run a "
      ++ "test-suite and get its full output.\n",
914
915
916
917
    commandNotes        = Just $ \pname ->
          "Examples:\n"
       ++ "  " ++ pname ++ " run\n"
       ++ "    Run the only executable in the current package;\n"
918
919
       ++ "  " ++ pname ++ " run foo -- --fooflag\n"
       ++ "    Works similar to `./foo --fooflag`.\n",
920
921
    commandUsage        = usageAlternatives "run"
        ["[FLAGS] [EXECUTABLE] [-- EXECUTABLE_FLAGS]"],
refold's avatar
refold committed
922
    commandDefaultFlags = mempty,
923
924
    commandOptions      =
      \showOrParseArgs -> liftOptions fst setFst
925
                          (commandOptions parent showOrParseArgs)
926
927
928
                          ++
                          liftOptions snd setSnd
                          (buildExOptions showOrParseArgs)
refold's avatar
refold committed
929
930
  }
  where
931
932
933
    setFst a (_,b) = (a,b)
    setSnd b (a,_) = (a,b)

934
    parent = Cabal.buildCommand defaultProgramConfiguration
refold's avatar
refold committed
935

936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
-- ------------------------------------------------------------
-- * 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
954
955
956
reportCommand = CommandUI {
    commandName         = "report",
    commandSynopsis     = "Upload build reports to a remote server.",
957
958
    commandDescription  = Nothing,
    commandNotes        = Just $ \_ ->
959
         "You can store your Hackage login in the ~/.cabal/config file\n",
960
    commandUsage        = usageAlternatives "report" ["[FLAGS]"],
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
    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))
      ]
977
978
  }

979
980
981
982
983
984
985
986
987
988
989
990
991
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

992
-- ------------------------------------------------------------
993
-- * Get flags
994
995
-- ------------------------------------------------------------

996
997
998
999
1000
data GetFlags = GetFlags {
    getDestDir          :: Flag FilePath,
    getPristine         :: Flag Bool,
    getSourceRepository :: Flag (Maybe RepoKind),
    getVerbosity        :: Flag Verbosity