Setup.hs 98.3 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
    , configPackageDB', configCompilerAux'
22
    , configureExCommand, ConfigExFlags(..), defaultConfigExFlags
23
    , buildCommand, BuildFlags(..), BuildExFlags(..), SkipAddSourceDepsCheck(..)
24
    , replCommand, testCommand, benchmarkCommand
ttuegel's avatar
ttuegel committed
25
                        , configureExOptions, reconfigureCommand
26
    , installCommand, InstallFlags(..), installOptions, defaultInstallFlags
27
    , defaultSolver, defaultMaxBackjumps
28
    , listCommand, ListFlags(..)
Duncan Coutts's avatar
Duncan Coutts committed
29
    , updateCommand
ijones's avatar
ijones committed
30
    , upgradeCommand
31
    , uninstallCommand
32
    , infoCommand, InfoFlags(..)
33
    , fetchCommand, FetchFlags(..)
34
    , freezeCommand, FreezeFlags(..)
35
    , genBoundsCommand
36
    , outdatedCommand, OutdatedFlags(..), IgnoreMajorVersionBumps(..)
37
    , getCommand, unpackCommand, GetFlags(..)
38
    , checkCommand
39
    , formatCommand
40
    , uploadCommand, UploadFlags(..), IsCandidate(..)
41
    , reportCommand, ReportFlags(..)
refold's avatar
refold committed
42
    , runCommand
43
    , initCommand, IT.InitFlags(..)
44
    , sdistCommand, SDistFlags(..), SDistExFlags(..), ArchiveFormat(..)
45
    , win32SelfUpgradeCommand, Win32SelfUpgradeFlags(..)
46
    , actAsSetupCommand, ActAsSetupFlags(..)
refold's avatar
refold committed
47
    , sandboxCommand, defaultSandboxLocation, SandboxFlags(..)
48
    , execCommand, ExecFlags(..)
49
    , userConfigCommand, UserConfigFlags(..)
Maciek Makowski's avatar
Maciek Makowski committed
50
    , manpageCommand
Duncan Coutts's avatar
Duncan Coutts committed
51 52

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

59 60 61
import Prelude ()
import Distribution.Client.Compat.Prelude hiding (get)

62
import Distribution.Client.Types
63
         ( Username(..), Password(..), RemoteRepo(..) )
64 65
import Distribution.Client.BuildReports.Types
         ( ReportLevel(..) )
66
import Distribution.Client.Dependency.Types
67
         ( PreSolver(..) )
68 69
import Distribution.Client.IndexUtils.Timestamp
         ( IndexState )
70 71
import qualified Distribution.Client.Init.Types as IT
         ( InitFlags(..), PackageType(..) )
72 73
import Distribution.Client.Targets
         ( UserConstraint, readUserConstraint )
74 75
import Distribution.Utils.NubList
         ( NubList, toNubList, fromNubList)
76

77
import Distribution.Solver.Types.ConstraintSource
78
import Distribution.Solver.Types.Settings
79

80 81
import Distribution.Simple.Compiler ( Compiler, PackageDB, PackageDBStack )
import Distribution.Simple.Program (ProgramDb, defaultProgramDb)
82 83
import Distribution.Simple.Command hiding (boolOpt, boolOpt')
import qualified Distribution.Simple.Command as Command
84
import Distribution.Simple.Configure
85
       ( configCompilerAuxEx, interpretPackageDbFlags, computeEffectiveProfiling )
Duncan Coutts's avatar
Duncan Coutts committed
86
import qualified Distribution.Simple.Setup as Cabal
87
import Distribution.Simple.Setup
88 89
         ( ConfigFlags(..), BuildFlags(..), ReplFlags
         , TestFlags(..), BenchmarkFlags(..)
90
         , SDistFlags(..), HaddockFlags(..)
91
         , readPackageDbList, showPackageDbList
Edsko de Vries's avatar
Edsko de Vries committed
92
         , Flag(..), toFlag, flagToMaybe, flagToList
93 94
         , BooleanFlag(..), optionVerbosity
         , boolOpt, boolOpt', trueArg, falseArg
95
         , optionNumJobs )
96
import Distribution.Simple.InstallDirs
Christiaan Baaij's avatar
Christiaan Baaij committed
97
         ( PathTemplate, InstallDirs(dynlibdir, sysconfdir)
98
         , toPathTemplate, fromPathTemplate )
99
import Distribution.Version
100
         ( Version, mkVersion, nullVersion, anyVersion, thisVersion )
101
import Distribution.Package
102
         ( PackageIdentifier, PackageName, packageName, packageVersion )
103
import Distribution.Types.Dependency
104
import Distribution.PackageDescription
105
         ( BuildType(..), RepoKind(..) )
106
import Distribution.System ( Platform )
107
import Distribution.Text
108
         ( Text(..), display )
109
import Distribution.ReadE
110
         ( ReadE(..), readP_to_E, succeedReadE )
111
import qualified Distribution.Compat.ReadP as Parse
112
         ( ReadP, char, munch1, pfail, sepBy1, (+++) )
113 114
import Distribution.ParseUtils
         ( readPToMaybe )
115
import Distribution.Verbosity
116
         ( Verbosity, lessVerbose, normal, verboseNoFlags )
117
import Distribution.Simple.Utils
118
         ( wrapText, wrapLine )
119
import Distribution.Client.GlobalFlags
Edsko de Vries's avatar
Edsko de Vries committed
120 121 122
         ( GlobalFlags(..), defaultGlobalFlags
         , RepoContext(..), withRepoContext
         )
123

124
import Data.List
125
         ( deleteFirstsBy )
126 127 128 129
import System.FilePath
         ( (</>) )
import Network.URI
         ( parseAbsoluteURI, uriToString )
130

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

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

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

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

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

295
      ,option [] ["ignore-expiry"]
Edsko de Vries's avatar
Edsko de Vries committed
296
         "Ignore expiry dates on signed metadata (use only in exceptional circumstances)"
297 298 299
         globalIgnoreExpiry (\v flags -> flags { globalIgnoreExpiry = v })
         trueArg

300
      ,option [] ["http-transport"]
301
         "Set a transport for http(s) requests. Accepts 'curl', 'wget', 'powershell', and 'plain-http'. (default: 'curl')"
302
         globalHttpTransport (\v flags -> flags { globalHttpTransport = v })
303
         (reqArgFlag "HttpTransport")
ttuegel's avatar
ttuegel committed
304 305 306 307
      ,option [] ["nix"]
         "Nix integration: run commands through nix-shell if a 'shell.nix' file exists"
         globalNix (\v flags -> flags { globalNix = v })
         (boolOpt [] [])
308
      ]
309

310 311 312 313
    -- arguments we don't want shown in the help
    argsNotShown :: [OptionField GlobalFlags]
    argsNotShown = [
       option [] ["remote-repo"]
314 315
         "The name and url for a remote repository"
         globalRemoteRepos (\v flags -> flags { globalRemoteRepos = v })
316
         (reqArg' "NAME:URL" (toNubList . maybeToList . readRepo) (map showRepo . fromNubList))
317 318 319 320 321 322 323 324 325

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

328 329 330 331 332
      ,option [] ["logs-dir"]
         "The location to put log files"
         globalLogsDir (\v flags -> flags { globalLogsDir = v })
         (reqArgFlag "DIR")

333 334 335 336
      ,option [] ["world-file"]
         "The location of the world file"
         globalWorldFile (\v flags -> flags { globalWorldFile = v })
         (reqArgFlag "FILE")
337 338 339 340 341
      ]

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

343
configureCommand :: CommandUI ConfigFlags
344 345
configureCommand = c
  { commandDefaultFlags = mempty
346 347 348
  , commandNotes = Just $ \pname -> (case commandNotes c of
         Nothing -> ""
         Just n  -> n pname ++ "\n")
349 350 351 352 353 354
       ++ "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
355
  }
356
 where
357
  c = Cabal.configureCommand defaultProgramDb
Duncan Coutts's avatar
Duncan Coutts committed
358

359 360 361
configureOptions ::  ShowOrParseArgs -> [OptionField ConfigFlags]
configureOptions = commandOptions configureCommand

362 363 364 365 366 367 368 369
-- | Given some 'ConfigFlags' for the version of Cabal that
-- cabal-install was built with, and a target older 'Version' of
-- Cabal that we want to pass these flags to, convert the
-- flags into a form that will be accepted by the older
-- Setup script.  Generally speaking, this just means filtering
-- out flags that the old Cabal library doesn't understand, but
-- in some cases it may also mean "emulating" a feature using
-- some more legacy flags.
370
filterConfigureFlags :: ConfigFlags -> Version -> ConfigFlags
371
filterConfigureFlags flags cabalLibVersion
372 373
  -- NB: we expect the latest version to be the most common case,
  -- so test it first.
Christiaan Baaij's avatar
Christiaan Baaij committed
374
  | cabalLibVersion >= mkVersion [1,25,0] = flags_latest
375 376 377 378 379
  -- The naming convention is that flags_version gives flags with
  -- all flags *introduced* in version eliminated.
  -- It is NOT the latest version of Cabal library that
  -- these flags work for; version of introduction is a more
  -- natural metric.
380 381 382 383 384 385 386 387 388 389
  | cabalLibVersion < mkVersion [1,3,10] = flags_1_3_10
  | cabalLibVersion < mkVersion [1,10,0] = flags_1_10_0
  | cabalLibVersion < mkVersion [1,12,0] = flags_1_12_0
  | cabalLibVersion < mkVersion [1,14,0] = flags_1_14_0
  | cabalLibVersion < mkVersion [1,18,0] = flags_1_18_0
  | cabalLibVersion < mkVersion [1,19,1] = flags_1_19_1
  | cabalLibVersion < mkVersion [1,19,2] = flags_1_19_2
  | cabalLibVersion < mkVersion [1,21,1] = flags_1_21_1
  | cabalLibVersion < mkVersion [1,22,0] = flags_1_22_0
  | cabalLibVersion < mkVersion [1,23,0] = flags_1_23_0
Christiaan Baaij's avatar
Christiaan Baaij committed
390
  | cabalLibVersion < mkVersion [1,25,0] = flags_1_25_0
391
  | otherwise = flags_latest
392
  where
393 394 395
    flags_latest = flags        {
      -- Cabal >= 1.19.1 uses '--dependency' and does not need '--constraint'.
      configConstraints = [],
396
      -- Passing '--allow-{older,newer}' to Setup.hs is unnecessary, we use
397
      -- '--exact-configuration' instead.
398
      configAllowOlder  = Just (Cabal.AllowOlder Cabal.RelaxDepsNone),
399
      configAllowNewer  = Just (Cabal.AllowNewer Cabal.RelaxDepsNone)
400
      }
401

402 403 404 405 406 407
    flags_1_25_0 = flags_latest {
      -- Cabal < 1.25.0 doesn't know about --dynlibdir.
      configInstallDirs = configInstallDirs_1_25_0,
      -- Cabal < 1.25 doesn't have extended verbosity syntax
      configVerbosity   = fmap verboseNoFlags (configVerbosity flags_latest)
      }
Christiaan Baaij's avatar
Christiaan Baaij committed
408 409
    configInstallDirs_1_25_0 = (configInstallDirs flags) { dynlibdir = NoFlag }

410
    -- Cabal < 1.23 doesn't know about '--profiling-detail'.
411 412 413
    -- Cabal < 1.23 has a hacked up version of 'enable-profiling'
    -- which we shouldn't use.
    (tryLibProfiling, tryExeProfiling) = computeEffectiveProfiling flags
Christiaan Baaij's avatar
Christiaan Baaij committed
414
    flags_1_23_0 = flags_1_25_0 { configProfDetail    = NoFlag
415
                                , configProfLibDetail = NoFlag
416
                                , configIPID          = NoFlag
Mikhail Glushenkov's avatar
Mikhail Glushenkov committed
417 418 419
                                , configProf          = NoFlag
                                , configProfExe       = Flag tryExeProfiling
                                , configProfLib       = Flag tryLibProfiling
420
                                }
421

422
    -- Cabal < 1.22 doesn't know about '--disable-debug-info'.
423
    flags_1_22_0 = flags_1_23_0 { configDebugInfo = NoFlag }
424

425
    -- Cabal < 1.21.1 doesn't know about 'disable-relocatable'
426
    -- Cabal < 1.21.1 doesn't know about 'enable-profiling'
427
    -- (but we already dealt with it in flags_1_23_0)
428 429
    flags_1_21_1 =
      flags_1_22_0 { configRelocatable = NoFlag
430 431
                   , configCoverage = NoFlag
                   , configLibCoverage = configCoverage flags
432
                   }
433 434
    -- Cabal < 1.19.2 doesn't know about '--exact-configuration' and
    -- '--enable-library-stripping'.
435
    flags_1_19_2 = flags_1_21_1 { configExactConfiguration = NoFlag
436
                                , configStripLibs = NoFlag }
437
    -- Cabal < 1.19.1 uses '--constraint' instead of '--dependency'.
438
    flags_1_19_1 = flags_1_19_2 { configDependencies = []
439
                                , configConstraints  = configConstraints flags }
440
    -- Cabal < 1.18.0 doesn't know about --extra-prog-path and --sysconfdir.
441
    flags_1_18_0 = flags_1_19_1 { configProgramPathExtra = toNubList []
442
                                , configInstallDirs = configInstallDirs_1_18_0}
Christiaan Baaij's avatar
Christiaan Baaij committed
443
    configInstallDirs_1_18_0 = (configInstallDirs flags_1_19_1) { sysconfdir = NoFlag }
444
    -- Cabal < 1.14.0 doesn't know about '--disable-benchmarks'.
445
    flags_1_14_0 = flags_1_18_0 { configBenchmarks  = NoFlag }
446 447 448 449
    -- 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 }
450
    -- Cabal < 1.10.0 doesn't know about '--disable-tests'.
451
    flags_1_10_0 = flags_1_12_0 { configTests       = NoFlag }
452
    -- Cabal < 1.3.10 does not grok the '--constraints' flag.
453
    flags_1_3_10 = flags_1_10_0 { configConstraints = [] }
454

455 456
-- | Get the package database settings from 'ConfigFlags', accounting for
-- @--package-db@ and @--user@ flags.
457 458 459 460 461 462
configPackageDB' :: ConfigFlags -> PackageDBStack
configPackageDB' cfg =
    interpretPackageDbFlags userInstall (configPackageDBs cfg)
  where
    userInstall = Cabal.fromFlagOrDefault True (configUserInstall cfg)

463
-- | Configure the compiler, but reduce verbosity during this step.
464 465 466 467 468 469
configCompilerAux' :: ConfigFlags -> IO (Compiler, Platform, ProgramDb)
configCompilerAux' configFlags =
  configCompilerAuxEx configFlags
    --FIXME: make configCompilerAux use a sensible verbosity
    { configVerbosity = fmap lessVerbose (configVerbosity configFlags) }

470 471 472 473 474 475 476 477
-- ------------------------------------------------------------
-- * Config extra flags
-- ------------------------------------------------------------

-- | cabal configure takes some extra flags beyond runghc Setup configure
--
data ConfigExFlags = ConfigExFlags {
    configCabalVersion :: Flag Version,
478
    configExConstraints:: [(UserConstraint, ConstraintSource)],
479
    configPreferences  :: [Dependency],
480
    configSolver       :: Flag PreSolver
481
  }
482
  deriving (Eq, Generic)
483 484

defaultConfigExFlags :: ConfigExFlags
485
defaultConfigExFlags = mempty { configSolver     = Flag defaultSolver }
486 487 488 489 490

configureExCommand :: CommandUI (ConfigFlags, ConfigExFlags)
configureExCommand = configureCommand {
    commandDefaultFlags = (mempty, defaultConfigExFlags),
    commandOptions      = \showOrParseArgs ->
491
         liftOptions fst setFst
492
         (filter ((`notElem` ["constraint", "dependency", "exact-configuration"])
493
                  . optionName) $ configureOptions  showOrParseArgs)
494 495
      ++ liftOptions snd setSnd
         (configureExOptions showOrParseArgs ConstraintSourceCommandlineFlag)
496 497 498 499 500
  }
  where
    setFst a (_,b) = (a,b)
    setSnd b (a,_) = (a,b)

501 502 503 504
configureExOptions :: ShowOrParseArgs
                   -> ConstraintSource
                   -> [OptionField ConfigExFlags]
configureExOptions _showOrParseArgs src =
505 506 507 508 509 510 511
  [ 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))
512 513 514 515
  , option [] ["constraint"]
      "Specify constraints on a package (version, installed/source, flags)"
      configExConstraints (\v flags -> flags { configExConstraints = v })
      (reqArg "CONSTRAINT"
516 517
              ((\x -> [(x, src)]) `fmap` ReadE readUserConstraint)
              (map $ display . fst))
518 519 520 521

  , option [] ["preference"]
      "Specify preferences (soft constraints) on the version of a package"
      configPreferences (\v flags -> flags { configPreferences = v })
522 523 524 525
      (reqArg "CONSTRAINT"
              (readP_to_E (const "dependency expected")
                          (fmap (\x -> [x]) parse))
              (map display))
526 527

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

529 530 531
  ]

instance Monoid ConfigExFlags where
532
  mempty = gmempty
533 534 535
  mappend = (<>)

instance Semigroup ConfigExFlags where
536
  (<>) = gmappend
537

ttuegel's avatar
ttuegel committed
538 539 540 541 542 543
reconfigureCommand :: CommandUI (ConfigFlags, ConfigExFlags)
reconfigureCommand
  = configureExCommand
    { commandName         = "reconfigure"
    , commandSynopsis     = "Reconfigure the package if necessary."
    , commandDescription  = Just $ \pname -> wrapText $
544 545
         "Run `configure` with the most recently used flags, or append FLAGS "
         ++ "to the most recently used configuration. "
ttuegel's avatar
ttuegel committed
546
         ++ "Accepts the same flags as `" ++ pname ++ " configure'. "
547 548 549 550 551 552 553 554 555
         ++ "If the package has never been configured, the default flags are "
         ++ "used."
    , commandNotes        = Just $ \pname ->
        "Examples:\n"
        ++ "  " ++ pname ++ " reconfigure\n"
        ++ "    Configure with the most recently used flags.\n"
        ++ "  " ++ pname ++ " reconfigure -w PATH\n"
        ++ "    Reconfigure with the most recently used flags,\n"
        ++ "    but use the compiler at PATH.\n\n"
ttuegel's avatar
ttuegel committed
556 557 558 559
    , commandUsage        = usageAlternatives "reconfigure" [ "[FLAGS]" ]
    , commandDefaultFlags = mempty
    }

ttuegel's avatar
ttuegel committed
560 561 562 563
-- ------------------------------------------------------------
-- * Build flags
-- ------------------------------------------------------------

564 565 566 567 568 569
data SkipAddSourceDepsCheck =
  SkipAddSourceDepsCheck | DontSkipAddSourceDepsCheck
  deriving Eq

data BuildExFlags = BuildExFlags {
  buildOnly     :: Flag SkipAddSourceDepsCheck
570
} deriving Generic
571 572 573

buildExOptions :: ShowOrParseArgs -> [OptionField BuildExFlags]
buildExOptions _showOrParseArgs =
574
  option [] ["only"]
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
  "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)

594
    parent = Cabal.buildCommand defaultProgramDb
595 596

instance Monoid BuildExFlags where
597
  mempty = gmempty
598 599 600
  mappend = (<>)

instance Semigroup BuildExFlags where
601
  (<>) = gmappend
602 603

-- ------------------------------------------------------------
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
-- * 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)

620
    parent = Cabal.replCommand defaultProgramDb
621

622 623 624 625
-- ------------------------------------------------------------
-- * Test command
-- ------------------------------------------------------------

626
testCommand :: CommandUI (TestFlags, BuildFlags, BuildExFlags)
627
testCommand = parent {
628 629
  commandDefaultFlags = (commandDefaultFlags parent,
                         Cabal.defaultBuildFlags, mempty),
630
  commandOptions      =
631
    \showOrParseArgs -> liftOptions get1 set1
632 633
                        (commandOptions parent showOrParseArgs)
                        ++
634
                        liftOptions get2 set2
Mikhail Glushenkov's avatar
Mikhail Glushenkov committed
635
                        (Cabal.buildOptions progDb showOrParseArgs)
636 637
                        ++
                        liftOptions get3 set3 (buildExOptions showOrParseArgs)
638 639
  }
  where
640 641 642
    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)
643

Mikhail Glushenkov's avatar
Mikhail Glushenkov committed
644 645
    parent = Cabal.testCommand
    progDb = defaultProgramDb
646 647 648 649 650

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

651
benchmarkCommand :: CommandUI (BenchmarkFlags, BuildFlags, BuildExFlags)
652
benchmarkCommand = parent {
653 654
  commandDefaultFlags = (commandDefaultFlags parent,
                         Cabal.defaultBuildFlags, mempty),
655
  commandOptions      =
656
    \showOrParseArgs -> liftOptions get1 set1
657 658
                        (commandOptions parent showOrParseArgs)
                        ++
659
                        liftOptions get2 set2
Mikhail Glushenkov's avatar
Mikhail Glushenkov committed
660
                        (Cabal.buildOptions progDb showOrParseArgs)
661 662
                        ++
                        liftOptions get3 set3 (buildExOptions showOrParseArgs)
ttuegel's avatar
ttuegel committed
663
  }
664
  where
665 666 667
    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)
668

Mikhail Glushenkov's avatar
Mikhail Glushenkov committed
669 670
    parent = Cabal.benchmarkCommand
    progDb = defaultProgramDb
ttuegel's avatar
ttuegel committed
671

672
-- ------------------------------------------------------------
673
-- * Fetch command
674
-- ------------------------------------------------------------
675

676 677 678 679
data FetchFlags = FetchFlags {
--    fetchOutput    :: Flag FilePath,
      fetchDeps      :: Flag Bool,
      fetchDryRun    :: Flag Bool,
680
      fetchSolver           :: Flag PreSolver,
681
      fetchMaxBackjumps     :: Flag Int,
682
      fetchReorderGoals     :: Flag ReorderGoals,
683
      fetchCountConflicts   :: Flag CountConflicts,
684 685 686
      fetchIndependentGoals :: Flag IndependentGoals,
      fetchShadowPkgs       :: Flag ShadowPkgs,
      fetchStrongFlags      :: Flag StrongFlags,
687
      fetchAllowBootLibInstalls :: Flag AllowBootLibInstalls,
688 689 690 691 692 693 694 695
      fetchVerbosity :: Flag Verbosity
    }

defaultFetchFlags :: FetchFlags
defaultFetchFlags = FetchFlags {
--  fetchOutput    = mempty,
    fetchDeps      = toFlag True,
    fetchDryRun    = toFlag False,
696 697
    fetchSolver           = Flag defaultSolver,
    fetchMaxBackjumps     = Flag defaultMaxBackjumps,
698
    fetchReorderGoals     = Flag (ReorderGoals False),
699
    fetchCountConflicts   = Flag (CountConflicts True),
700 701 702
    fetchIndependentGoals = Flag (IndependentGoals False),
    fetchShadowPkgs       = Flag (ShadowPkgs False),
    fetchStrongFlags      = Flag (StrongFlags False),
703
    fetchAllowBootLibInstalls = Flag (AllowBootLibInstalls False),
704 705 706 707
    fetchVerbosity = toFlag normal
   }

fetchCommand :: CommandUI FetchFlags
Duncan Coutts's avatar
Duncan Coutts committed
708 709
fetchCommand = CommandUI {
    commandName         = "fetch",
710
    commandSynopsis     = "Downloads packages for later installation.",
711 712 713 714 715
    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",
716
    commandNotes        = Nothing,
717
    commandDefaultFlags = defaultFetchFlags,
718
    commandOptions      = \ showOrParseArgs -> [
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
         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
740 741 742 743

       ] ++

       optionSolver      fetchSolver           (\v flags -> flags { fetchSolver           = v }) :
744 745
       optionSolverFlags showOrParseArgs
                         fetchMaxBackjumps     (\v flags -> flags { fetchMaxBackjumps     = v })
746
                         fetchReorderGoals     (\v flags -> flags { fetchReorderGoals     = v })
747
                         fetchCountConflicts   (\v flags -> flags { fetchCountConflicts   = v })
748
                         fetchIndependentGoals (\v flags -> flags { fetchIndependentGoals = v })
749
                         fetchShadowPkgs       (\v flags -> flags { fetchShadowPkgs       = v })
Andres Löh's avatar
Andres Löh committed
750
                         fetchStrongFlags      (\v flags -> flags { fetchStrongFlags      = v })
751
                         fetchAllowBootLibInstalls (\v flags -> flags { fetchAllowBootLibInstalls = v })
752

Duncan Coutts's avatar
Duncan Coutts committed
753 754
  }

755 756 757 758 759 760
-- ------------------------------------------------------------
-- * Freeze command
-- ------------------------------------------------------------

data FreezeFlags = FreezeFlags {
      freezeDryRun           :: Flag Bool,
761 762
      freezeTests            :: Flag Bool,
      freezeBenchmarks       :: Flag Bool,
763 764
      freezeSolver           :: Flag PreSolver,
      freezeMaxBackjumps     :: Flag Int,
765
      freezeReorderGoals     :: Flag ReorderGoals,
766
      freezeCountConflicts   :: Flag CountConflicts,
767 768 769
      freezeIndependentGoals :: Flag IndependentGoals,
      freezeShadowPkgs       :: Flag ShadowPkgs,
      freezeStrongFlags      :: Flag StrongFlags,
770
      freezeAllowBootLibInstalls :: Flag AllowBootLibInstalls,
771 772 773 774 775 776
      freezeVerbosity        :: Flag Verbosity
    }

defaultFreezeFlags :: FreezeFlags
defaultFreezeFlags = FreezeFlags {
    freezeDryRun           = toFlag False,
777 778
    freezeTests            = toFlag False,
    freezeBenchmarks       = toFlag False,
779 780
    freezeSolver           = Flag defaultSolver,
    freezeMaxBackjumps     = Flag defaultMaxBackjumps,
781
    freezeReorderGoals     = Flag (ReorderGoals False),
782
    freezeCountConflicts   = Flag (CountConflicts True),
783 784 785
    freezeIndependentGoals = Flag (IndependentGoals False),
    freezeShadowPkgs       = Flag (ShadowPkgs False),
    freezeStrongFlags      = Flag (StrongFlags False),
786
    freezeAllowBootLibInstalls = Flag (AllowBootLibInstalls False),
787 788 789 790 791 792 793
    freezeVerbosity        = toFlag normal
   }

freezeCommand :: CommandUI FreezeFlags
freezeCommand = CommandUI {
    commandName         = "freeze",
    commandSynopsis     = "Freeze dependencies.",
794 795 796 797 798 799 800 801
    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",
802
    commandNotes        = Nothing,
803
    commandUsage        = usageFlags "freeze",
804 805
    commandDefaultFlags = defaultFreezeFlags,
    commandOptions      = \ showOrParseArgs -> [
806 807
         optionVerbosity freezeVerbosity
         (\v flags -> flags { freezeVerbosity = v })
808 809 810 811 812 813

       , option [] ["dry-run"]
           "Do not freeze anything, only print what would be frozen"
           freezeDryRun (\v flags -> flags { freezeDryRun = v })
           trueArg

814
       , option [] ["tests"]
815 816
           ("freezing of the dependencies of any tests suites "
            ++ "in the package description file.")
817 818 819 820
           freezeTests (\v flags -> flags { freezeTests = v })
           (boolOpt [] [])

       , option [] ["benchmarks"]
821 822
           ("freezing of the dependencies of any benchmarks suites "
            ++ "in the package description file.")
823 824 825
           freezeBenchmarks (\v flags -> flags { freezeBenchmarks = v })
           (boolOpt [] [])

826 827
       ] ++

828 829
       optionSolver
         freezeSolver           (\v flags -> flags { freezeSolver           = v }):
830 831 832
       optionSolverFlags showOrParseArgs
                         freezeMaxBackjumps     (\v flags -> flags { freezeMaxBackjumps     = v })
                         freezeReorderGoals     (\v flags -> flags { freezeReorderGoals     = v })
833
                         freezeCountConflicts   (\v flags -> flags { freezeCountConflicts   = v })
834 835
                         freezeIndependentGoals (\v flags -> flags { freezeIndependentGoals = v })
                         freezeShadowPkgs       (\v flags -> flags { freezeShadowPkgs       = v })
Andres Löh's avatar
Andres Löh committed
836
                         freezeStrongFlags      (\v flags -> flags { freezeStrongFlags      = v })
837
                         freezeAllowBootLibInstalls (\v flags -> flags { freezeAllowBootLibInstalls = v })
838 839 840

  }

841 842 843 844
-- ------------------------------------------------------------
-- * 'gen-bounds' command
-- ------------------------------------------------------------

845 846 847 848 849 850
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. "
851 852
      ++ "Generated bounds are printed to stdout.  "
      ++ "You can then paste them into your .cabal file.\n"
853 854 855 856 857 858 859 860 861
      ++ "\n",
    commandNotes        = Nothing,
    commandUsage        = usageFlags "gen-bounds",
    commandDefaultFlags = defaultFreezeFlags,
    commandOptions      = \ _ -> [
     optionVerbosity freezeVerbosity (\v flags -> flags { freezeVerbosity = v })
     ]
  }

862 863 864 865
-- ------------------------------------------------------------
-- * 'outdated' command
-- ------------------------------------------------------------

866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
data IgnoreMajorVersionBumps = IgnoreMajorVersionBumpsNone
                             | IgnoreMajorVersionBumpsAll
                             | IgnoreMajorVersionBumpsSome [PackageName]

instance Monoid IgnoreMajorVersionBumps where
  mempty  = IgnoreMajorVersionBumpsNone
  mappend = (<>)

instance Semigroup IgnoreMajorVersionBumps where
  IgnoreMajorVersionBumpsNone       <> r                               = r
  l@IgnoreMajorVersionBumpsAll      <> _                               = l
  l@(IgnoreMajorVersionBumpsSome _) <> IgnoreMajorVersionBumpsNone     = l
  (IgnoreMajorVersionBumpsSome   _) <> r@IgnoreMajorVersionBumpsAll    = r
  (IgnoreMajorVersionBumpsSome   a) <> (IgnoreMajorVersionBumpsSome b) =
    IgnoreMajorVersionBumpsSome (a ++ b)

882
data OutdatedFlags = OutdatedFlags {
883 884 885
  outdatedVerbosity     :: Flag Verbosity,
  outdatedFreezeFile    :: Flag Bool,
  outdatedNewFreezeFile :: Flag Bool,
886
  outdatedSimpleOutput  :: Flag Bool,
887
  outdatedExitCode      :: Flag Bool,
888
  outdatedQuiet         :: Flag Bool,
889
  outdatedIgnore        :: [PackageName],
890
  outdatedMinor         :: Maybe IgnoreMajorVersionBumps
891 892 893 894