Setup.hs 104 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(..)
Moritz Angermann's avatar
Moritz Angermann committed
29
    , updateCommand, UpdateFlags(..), defaultUpdateFlags
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(..)
Daniel Wagner's avatar
Daniel Wagner committed
48
    , execCommand, ExecFlags(..), defaultExecFlags
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 64 65
         ( Username(..), Password(..), RemoteRepo(..)
         , AllowNewer(..), AllowOlder(..), RelaxDeps(..)
         )
66 67
import Distribution.Client.BuildReports.Types
         ( ReportLevel(..) )
68
import Distribution.Client.Dependency.Types
69
         ( PreSolver(..) )
70
import Distribution.Client.IndexUtils.Timestamp
71
         ( IndexState(..) )
72 73
import qualified Distribution.Client.Init.Types as IT
         ( InitFlags(..), PackageType(..) )
74 75
import Distribution.Client.Targets
         ( UserConstraint, readUserConstraint )
76 77
import Distribution.Utils.NubList
         ( NubList, toNubList, fromNubList)
78

79
import Distribution.Solver.Types.ConstraintSource
80
import Distribution.Solver.Types.Settings
81

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

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

133 134
globalCommand :: [Command action] -> CommandUI GlobalFlags
globalCommand commands = CommandUI {
135
    commandName         = "",
136 137
    commandSynopsis     =
         "Command line interface to the Haskell Cabal infrastructure.",
138 139 140 141
    commandUsage        = \pname ->
         "See http://www.haskell.org/cabal/ for more information.\n"
      ++ "\n"
      ++ "Usage: " ++ pname ++ " [GLOBAL FLAGS] [COMMAND [FLAGS]]\n",
142
    commandDescription  = Just $ \pname ->
143 144 145
      let
        commands' = commands ++ [commandAddAction helpCommandUI undefined]
        cmdDescs = getNormalCommandDescriptions commands'
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
        -- 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"
163
          , "reconfigure"
164 165 166 167 168 169 170 171 172 173 174
          , "build"
          , "clean"
          , "run"
          , "repl"
          , "test"
          , "bench"
          , "check"
          , "sdist"
          , "upload"
          , "report"
          , "freeze"
175
          , "gen-bounds"
176
          , "outdated"
Moritz Angermann's avatar
Moritz Angermann committed
177
          , "doctest"
178 179 180 181 182 183
          , "haddock"
          , "hscolour"
          , "copy"
          , "register"
          , "sandbox"
          , "exec"
184 185 186 187
          , "new-build"
          , "new-configure"
          , "new-repl"
          , "new-freeze"
188 189 190
          , "new-run"
          , "new-test"
          , "new-bench"
191
          , "new-haddock"
192
          ]
193 194
        maxlen    = maximum $ [length name | (name, _) <- cmdDescs]
        align str = str ++ replicate (maxlen - length str) ' '
195 196 197 198 199 200 201 202 203
        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
204 205
      in
         "Commands:\n"
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
      ++ 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"
236
        , addCmd "gen-bounds"
237
        , addCmd "outdated"
Moritz Angermann's avatar
Moritz Angermann committed
238
        , addCmd "doctest"
239 240 241 242
        , addCmd "haddock"
        , addCmd "hscolour"
        , addCmd "copy"
        , addCmd "register"
243
        , addCmd "reconfigure"
244 245
        , par
        , startGroup "sandbox"
246
        , addCmd "sandbox"
247 248
        , addCmd "exec"
        , addCmdCustom "repl" "Open interpreter with access to sandbox packages."
249 250 251 252 253
        , par
        , startGroup "new-style projects (beta)"
        , addCmd "new-build"
        , addCmd "new-configure"
        , addCmd "new-repl"
254 255 256
        , addCmd "new-run"
        , addCmd "new-test"
        , addCmd "new-bench"
257 258
        , addCmd "new-freeze"
        , addCmd "new-haddock"
259 260 261
        ] ++ if null otherCmds then [] else par
                                           :startGroup "other"
                                           :[addCmd n | n <- otherCmds])
262 263
      ++ "\n"
      ++ "For more information about a command use:\n"
264 265
      ++ "   " ++ pname ++ " COMMAND --help\n"
      ++ "or " ++ pname ++ " help COMMAND\n"
266
      ++ "\n"
267
      ++ "To install Cabal packages from hackage use:\n"
268 269
      ++ "  " ++ pname ++ " install foo [--dry-run]\n"
      ++ "\n"
270 271
      ++ "Occasionally you need to update the list of available packages:\n"
      ++ "  " ++ pname ++ " update\n",
272
    commandNotes = Nothing,
273
    commandDefaultFlags = mempty,
274 275 276 277 278 279 280 281 282 283 284
    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"]
285 286 287 288 289 290 291 292 293 294 295 296 297 298
         "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")

299
      ,option [] ["sandbox-config-file"]
300
         "Set an alternate location for the sandbox config file (default: './cabal.sandbox.config')"
301
         globalSandboxConfigFile (\v flags -> flags { globalSandboxConfigFile = v })
302 303
         (reqArgFlag "FILE")

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

309
      ,option [] ["require-sandbox"]
Mikhail Glushenkov's avatar
Mikhail Glushenkov committed
310
         "requiring the presence of a sandbox for sandbox-aware commands"
311 312 313
         globalRequireSandbox (\v flags -> flags { globalRequireSandbox = v })
         (boolOpt' ([], ["require-sandbox"]) ([], ["no-require-sandbox"]))

314 315 316 317 318
      ,option [] ["ignore-sandbox"]
         "Ignore any existing sandbox"
         globalIgnoreSandbox (\v flags -> flags { globalIgnoreSandbox = v })
         trueArg

319
      ,option [] ["ignore-expiry"]
Edsko de Vries's avatar
Edsko de Vries committed
320
         "Ignore expiry dates on signed metadata (use only in exceptional circumstances)"
321 322 323
         globalIgnoreExpiry (\v flags -> flags { globalIgnoreExpiry = v })
         trueArg

324
      ,option [] ["http-transport"]
325
         "Set a transport for http(s) requests. Accepts 'curl', 'wget', 'powershell', and 'plain-http'. (default: 'curl')"
326
         globalHttpTransport (\v flags -> flags { globalHttpTransport = v })
327
         (reqArgFlag "HttpTransport")
ttuegel's avatar
ttuegel committed
328 329 330 331
      ,option [] ["nix"]
         "Nix integration: run commands through nix-shell if a 'shell.nix' file exists"
         globalNix (\v flags -> flags { globalNix = v })
         (boolOpt [] [])
332
      ]
333

334 335 336 337
    -- arguments we don't want shown in the help
    argsNotShown :: [OptionField GlobalFlags]
    argsNotShown = [
       option [] ["remote-repo"]
338 339
         "The name and url for a remote repository"
         globalRemoteRepos (\v flags -> flags { globalRemoteRepos = v })
340
         (reqArg' "NAME:URL" (toNubList . maybeToList . readRepo) (map showRepo . fromNubList))
341 342 343 344 345 346 347 348 349

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

352 353 354 355 356
      ,option [] ["logs-dir"]
         "The location to put log files"
         globalLogsDir (\v flags -> flags { globalLogsDir = v })
         (reqArgFlag "DIR")

357 358 359 360
      ,option [] ["world-file"]
         "The location of the world file"
         globalWorldFile (\v flags -> flags { globalWorldFile = v })
         (reqArgFlag "FILE")
361 362 363 364 365

      ,option [] ["store-dir"]
         "The location of the nix-local-build store"
         globalStoreDir (\v flags -> flags { globalStoreDir = v })
         (reqArgFlag "DIR")
366 367 368 369 370
      ]

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

372
configureCommand :: CommandUI ConfigFlags
373 374
configureCommand = c
  { commandDefaultFlags = mempty
375 376 377
  , commandNotes = Just $ \pname -> (case commandNotes c of
         Nothing -> ""
         Just n  -> n pname ++ "\n")
378 379 380 381 382 383
       ++ "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
384
  }
385
 where
386
  c = Cabal.configureCommand defaultProgramDb
Duncan Coutts's avatar
Duncan Coutts committed
387

388 389 390
configureOptions ::  ShowOrParseArgs -> [OptionField ConfigFlags]
configureOptions = commandOptions configureCommand

391 392 393 394 395 396 397 398
-- | 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.
399
filterConfigureFlags :: ConfigFlags -> Version -> ConfigFlags
400
filterConfigureFlags flags cabalLibVersion
401 402
  -- NB: we expect the latest version to be the most common case,
  -- so test it first.
403
  | cabalLibVersion >= mkVersion [2,1,0]  = flags_latest
404 405 406 407 408
  -- 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.
409 410 411 412 413 414 415 416 417 418
  | 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
419
  | cabalLibVersion < mkVersion [1,25,0] = flags_1_25_0
420
  | cabalLibVersion < mkVersion [2,1,0]  = flags_2_1_0
421
  | otherwise = flags_latest
422
  where
423 424
    flags_latest = flags        {
      -- Cabal >= 1.19.1 uses '--dependency' and does not need '--constraint'.
425
      configConstraints = []
426
      }
427

428 429
    flags_2_1_0 = flags_latest {
      -- Cabal < 2.1 doesn't know about -v +timestamp modifier
Moritz Angermann's avatar
Moritz Angermann committed
430 431 432
        configVerbosity   = fmap verboseNoTimestamp (configVerbosity flags_latest)
      -- Cabal < 2.1 doesn't know about --<enable|disable>-static
      , configStaticLib   = NoFlag
Ben Gamari's avatar
Ben Gamari committed
433
      , configSplitSections = NoFlag
434 435 436
      }

    flags_1_25_0 = flags_2_1_0 {
437 438 439
      -- Cabal < 1.25.0 doesn't know about --dynlibdir.
      configInstallDirs = configInstallDirs_1_25_0,
      -- Cabal < 1.25 doesn't have extended verbosity syntax
440
      configVerbosity   = fmap verboseNoFlags (configVerbosity flags_2_1_0),
441 442
      -- Cabal < 1.25 doesn't support --deterministic
      configDeterministic = mempty
443
      }
444 445 446 447 448 449 450
    configInstallDirs_1_25_0 = let dirs = configInstallDirs flags in
        dirs { dynlibdir = NoFlag
             , libexecsubdir = NoFlag
             , libexecdir = maybeToFlag $
                 combinePathTemplate <$> flagToMaybe (libexecdir dirs)
                                     <*> flagToMaybe (libexecsubdir dirs)
             }
451
    -- Cabal < 1.23 doesn't know about '--profiling-detail'.
452 453 454
    -- 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
455
    flags_1_23_0 = flags_1_25_0 { configProfDetail    = NoFlag
456
                                , configProfLibDetail = NoFlag
457
                                , configIPID          = NoFlag
Mikhail Glushenkov's avatar
Mikhail Glushenkov committed
458 459 460
                                , configProf          = NoFlag
                                , configProfExe       = Flag tryExeProfiling
                                , configProfLib       = Flag tryLibProfiling
461
                                }
462

463
    -- Cabal < 1.22 doesn't know about '--disable-debug-info'.
464
    flags_1_22_0 = flags_1_23_0 { configDebugInfo = NoFlag }
465

466
    -- Cabal < 1.21.1 doesn't know about 'disable-relocatable'
467
    -- Cabal < 1.21.1 doesn't know about 'enable-profiling'
468
    -- (but we already dealt with it in flags_1_23_0)
469 470
    flags_1_21_1 =
      flags_1_22_0 { configRelocatable = NoFlag
471 472
                   , configCoverage = NoFlag
                   , configLibCoverage = configCoverage flags
473
                   }
474 475
    -- Cabal < 1.19.2 doesn't know about '--exact-configuration' and
    -- '--enable-library-stripping'.
476
    flags_1_19_2 = flags_1_21_1 { configExactConfiguration = NoFlag
477
                                , configStripLibs = NoFlag }
478
    -- Cabal < 1.19.1 uses '--constraint' instead of '--dependency'.
479
    flags_1_19_1 = flags_1_19_2 { configDependencies = []
480
                                , configConstraints  = configConstraints flags }
481
    -- Cabal < 1.18.0 doesn't know about --extra-prog-path and --sysconfdir.
482
    flags_1_18_0 = flags_1_19_1 { configProgramPathExtra = toNubList []
483
                                , configInstallDirs = configInstallDirs_1_18_0}
Christiaan Baaij's avatar
Christiaan Baaij committed
484
    configInstallDirs_1_18_0 = (configInstallDirs flags_1_19_1) { sysconfdir = NoFlag }
485
    -- Cabal < 1.14.0 doesn't know about '--disable-benchmarks'.
486
    flags_1_14_0 = flags_1_18_0 { configBenchmarks  = NoFlag }
487 488 489 490
    -- 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 }
491
    -- Cabal < 1.10.0 doesn't know about '--disable-tests'.
492
    flags_1_10_0 = flags_1_12_0 { configTests       = NoFlag }
493
    -- Cabal < 1.3.10 does not grok the '--constraints' flag.
494
    flags_1_3_10 = flags_1_10_0 { configConstraints = [] }
495

496 497
-- | Get the package database settings from 'ConfigFlags', accounting for
-- @--package-db@ and @--user@ flags.
498 499 500 501 502 503
configPackageDB' :: ConfigFlags -> PackageDBStack
configPackageDB' cfg =
    interpretPackageDbFlags userInstall (configPackageDBs cfg)
  where
    userInstall = Cabal.fromFlagOrDefault True (configUserInstall cfg)

504
-- | Configure the compiler, but reduce verbosity during this step.
505 506 507 508 509 510
configCompilerAux' :: ConfigFlags -> IO (Compiler, Platform, ProgramDb)
configCompilerAux' configFlags =
  configCompilerAuxEx configFlags
    --FIXME: make configCompilerAux use a sensible verbosity
    { configVerbosity = fmap lessVerbose (configVerbosity configFlags) }

511 512 513 514 515 516 517 518
-- ------------------------------------------------------------
-- * Config extra flags
-- ------------------------------------------------------------

-- | cabal configure takes some extra flags beyond runghc Setup configure
--
data ConfigExFlags = ConfigExFlags {
    configCabalVersion :: Flag Version,
519
    configExConstraints:: [(UserConstraint, ConstraintSource)],
520
    configPreferences  :: [Dependency],
521 522 523
    configSolver       :: Flag PreSolver,
    configAllowNewer   :: Maybe AllowNewer,
    configAllowOlder   :: Maybe AllowOlder
524
  }
525
  deriving (Eq, Generic)
526 527

defaultConfigExFlags :: ConfigExFlags
528
defaultConfigExFlags = mempty { configSolver     = Flag defaultSolver }
529 530 531 532 533

configureExCommand :: CommandUI (ConfigFlags, ConfigExFlags)
configureExCommand = configureCommand {
    commandDefaultFlags = (mempty, defaultConfigExFlags),
    commandOptions      = \showOrParseArgs ->
534
         liftOptions fst setFst
535
         (filter ((`notElem` ["constraint", "dependency", "exact-configuration"])
536
                  . optionName) $ configureOptions  showOrParseArgs)
537 538
      ++ liftOptions snd setSnd
         (configureExOptions showOrParseArgs ConstraintSourceCommandlineFlag)
539 540 541 542 543
  }
  where
    setFst a (_,b) = (a,b)
    setSnd b (a,_) = (a,b)

544 545 546 547
configureExOptions :: ShowOrParseArgs
                   -> ConstraintSource
                   -> [OptionField ConfigExFlags]
configureExOptions _showOrParseArgs src =
548 549 550 551 552 553 554
  [ 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))
555 556 557 558
  , option [] ["constraint"]
      "Specify constraints on a package (version, installed/source, flags)"
      configExConstraints (\v flags -> flags { configExConstraints = v })
      (reqArg "CONSTRAINT"
559 560
              ((\x -> [(x, src)]) `fmap` ReadE readUserConstraint)
              (map $ display . fst))
561 562 563 564

  , option [] ["preference"]
      "Specify preferences (soft constraints) on the version of a package"
      configPreferences (\v flags -> flags { configPreferences = v })
565 566 567 568
      (reqArg "CONSTRAINT"
              (readP_to_E (const "dependency expected")
                          (fmap (\x -> [x]) parse))
              (map display))
569 570

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

572
  , option [] ["allow-older"]
573
    ("Ignore lower bounds in all dependencies or DEPS")
574 575 576 577 578 579 580 581 582 583 584 585 586 587
    (fmap unAllowOlder . configAllowOlder)
    (\v flags -> flags { configAllowOlder = fmap AllowOlder v})
    (optArg "DEPS"
     (readP_to_E ("Cannot parse the list of packages: " ++) relaxDepsParser)
     (Just RelaxDepsAll) relaxDepsPrinter)

  , option [] ["allow-newer"]
    ("Ignore upper bounds in all dependencies or DEPS")
    (fmap unAllowNewer . configAllowNewer)
    (\v flags -> flags { configAllowNewer = fmap AllowNewer v})
    (optArg "DEPS"
     (readP_to_E ("Cannot parse the list of packages: " ++) relaxDepsParser)
     (Just RelaxDepsAll) relaxDepsPrinter)

588 589
  ]

590 591 592 593 594 595 596 597 598 599 600

relaxDepsParser :: Parse.ReadP r (Maybe RelaxDeps)
relaxDepsParser =
  (Just . RelaxDepsSome) `fmap` Parse.sepBy1 parse (Parse.char ',')

relaxDepsPrinter :: (Maybe RelaxDeps) -> [Maybe String]
relaxDepsPrinter Nothing                     = []
relaxDepsPrinter (Just RelaxDepsAll)         = [Nothing]
relaxDepsPrinter (Just (RelaxDepsSome pkgs)) = map (Just . display) $ pkgs


601
instance Monoid ConfigExFlags where
602
  mempty = gmempty
603 604 605
  mappend = (<>)

instance Semigroup ConfigExFlags where
606
  (<>) = gmappend
607

ttuegel's avatar
ttuegel committed
608 609 610 611 612 613
reconfigureCommand :: CommandUI (ConfigFlags, ConfigExFlags)
reconfigureCommand
  = configureExCommand
    { commandName         = "reconfigure"
    , commandSynopsis     = "Reconfigure the package if necessary."
    , commandDescription  = Just $ \pname -> wrapText $
614 615
         "Run `configure` with the most recently used flags, or append FLAGS "
         ++ "to the most recently used configuration. "
ttuegel's avatar
ttuegel committed
616
         ++ "Accepts the same flags as `" ++ pname ++ " configure'. "
617 618 619 620 621 622 623 624 625
         ++ "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
626 627 628 629
    , commandUsage        = usageAlternatives "reconfigure" [ "[FLAGS]" ]
    , commandDefaultFlags = mempty
    }

ttuegel's avatar
ttuegel committed
630 631 632 633
-- ------------------------------------------------------------
-- * Build flags
-- ------------------------------------------------------------

634 635 636 637 638 639
data SkipAddSourceDepsCheck =
  SkipAddSourceDepsCheck | DontSkipAddSourceDepsCheck
  deriving Eq

data BuildExFlags = BuildExFlags {
  buildOnly     :: Flag SkipAddSourceDepsCheck
640
} deriving Generic
641 642 643

buildExOptions :: ShowOrParseArgs -> [OptionField BuildExFlags]
buildExOptions _showOrParseArgs =
644
  option [] ["only"]
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
  "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)

664
    parent = Cabal.buildCommand defaultProgramDb
665 666

instance Monoid BuildExFlags where
667
  mempty = gmempty
668 669 670
  mappend = (<>)

instance Semigroup BuildExFlags where
671
  (<>) = gmappend
672 673

-- ------------------------------------------------------------
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
-- * 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)

690
    parent = Cabal.replCommand defaultProgramDb
691

692 693 694 695
-- ------------------------------------------------------------
-- * Test command
-- ------------------------------------------------------------

696
testCommand :: CommandUI (TestFlags, BuildFlags, BuildExFlags)
697
testCommand = parent {
698 699
  commandDefaultFlags = (commandDefaultFlags parent,
                         Cabal.defaultBuildFlags, mempty),
700
  commandOptions      =
701
    \showOrParseArgs -> liftOptions get1 set1
702 703
                        (commandOptions parent showOrParseArgs)
                        ++
704
                        liftOptions get2 set2
Mikhail Glushenkov's avatar
Mikhail Glushenkov committed
705
                        (Cabal.buildOptions progDb showOrParseArgs)
706 707
                        ++
                        liftOptions get3 set3 (buildExOptions showOrParseArgs)
708 709
  }
  where
710 711 712
    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)
713

Mikhail Glushenkov's avatar
Mikhail Glushenkov committed
714 715
    parent = Cabal.testCommand
    progDb = defaultProgramDb
716 717 718 719 720

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

721
benchmarkCommand :: CommandUI (BenchmarkFlags, BuildFlags, BuildExFlags)
722
benchmarkCommand = parent {
723 724
  commandDefaultFlags = (commandDefaultFlags parent,
                         Cabal.defaultBuildFlags, mempty),
725
  commandOptions      =
726
    \showOrParseArgs -> liftOptions get1 set1
727 728
                        (commandOptions parent showOrParseArgs)
                        ++
729
                        liftOptions get2 set2
Mikhail Glushenkov's avatar
Mikhail Glushenkov committed
730
                        (Cabal.buildOptions progDb showOrParseArgs)
731 732
                        ++
                        liftOptions get3 set3 (buildExOptions showOrParseArgs)
ttuegel's avatar
ttuegel committed
733
  }
734
  where
735 736 737
    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)
738

Mikhail Glushenkov's avatar
Mikhail Glushenkov committed
739 740
    parent = Cabal.benchmarkCommand
    progDb = defaultProgramDb
ttuegel's avatar
ttuegel committed
741

742
-- ------------------------------------------------------------
743
-- * Fetch command
744
-- ------------------------------------------------------------
745

746 747 748 749
data FetchFlags = FetchFlags {
--    fetchOutput    :: Flag FilePath,
      fetchDeps      :: Flag Bool,
      fetchDryRun    :: Flag Bool,
750
      fetchSolver           :: Flag PreSolver,
751
      fetchMaxBackjumps     :: Flag Int,
752
      fetchReorderGoals     :: Flag ReorderGoals,
753
      fetchCountConflicts   :: Flag CountConflicts,
754 755 756
      fetchIndependentGoals :: Flag IndependentGoals,
      fetchShadowPkgs       :: Flag ShadowPkgs,
      fetchStrongFlags      :: Flag StrongFlags,
757
      fetchAllowBootLibInstalls :: Flag AllowBootLibInstalls,
758 759
      fetchTests            :: Flag Bool,
      fetchBenchmarks       :: Flag Bool,
760 761 762 763 764 765 766 767
      fetchVerbosity :: Flag Verbosity
    }

defaultFetchFlags :: FetchFlags
defaultFetchFlags = FetchFlags {
--  fetchOutput    = mempty,
    fetchDeps      = toFlag True,
    fetchDryRun    = toFlag False,
768 769
    fetchSolver           = Flag defaultSolver,
    fetchMaxBackjumps     = Flag defaultMaxBackjumps,
770
    fetchReorderGoals     = Flag (ReorderGoals False),
771
    fetchCountConflicts   = Flag (CountConflicts True),
772 773 774
    fetchIndependentGoals = Flag (IndependentGoals False),
    fetchShadowPkgs       = Flag (ShadowPkgs False),
    fetchStrongFlags      = Flag (StrongFlags False),
775
    fetchAllowBootLibInstalls = Flag (AllowBootLibInstalls False),
776 777
    fetchTests            = toFlag False,
    fetchBenchmarks       = toFlag False,
778 779 780 781
    fetchVerbosity = toFlag normal
   }

fetchCommand :: CommandUI FetchFlags
Duncan Coutts's avatar
Duncan Coutts committed
782 783
fetchCommand = CommandUI {
    commandName         = "fetch",
784
    commandSynopsis     = "Downloads packages for later installation.",
785 786 787 788 789
    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",
790
    commandNotes        = Nothing,
791
    commandDefaultFlags = defaultFetchFlags,
792
    commandOptions      = \ showOrParseArgs -> [
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
         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
814

815 816 817 818 819 820 821 822 823 824
      , option "" ["tests"]
         "dependency checking and compilation for test suites listed in the package description file."
         fetchTests (\v flags -> flags { fetchTests = v })
         (boolOpt [] [])

      , option "" ["benchmarks"]
         "dependency checking and compilation for benchmarks listed in the package description file."
         fetchBenchmarks (\v flags -> flags { fetchBenchmarks = v })
         (boolOpt [] [])

825 826 827
       ] ++

       optionSolver      fetchSolver           (\v flags -> flags { fetchSolver           = v }) :
828 829
       optionSolverFlags showOrParseArgs
                         fetchMaxBackjumps     (\v flags -> flags { fetchMaxBackjumps     = v })
830
                         fetchReorderGoals     (\v flags -> flags { fetchReorderGoals     = v })
831
                         fetchCountConflicts   (\v flags -> flags { fetchCountConflicts   = v })
832
                         fetchIndependentGoals (\v flags -> flags { fetchIndependentGoals = v })
833
                         fetchShadowPkgs       (\v flags -> flags { fetchShadowPkgs       = v })
Andres Löh's avatar
Andres Löh committed
834
                         fetchStrongFlags      (\v flags -> flags { fetchStrongFlags      = v })
835
                         fetchAllowBootLibInstalls (\v flags -> flags { fetchAllowBootLibInstalls = v })
836

Duncan Coutts's avatar
Duncan Coutts committed
837 838
  }

839 840 841 842 843 844
-- ------------------------------------------------------------
-- * Freeze command
-- ------------------------------------------------------------

data FreezeFlags = FreezeFlags {
      freezeDryRun           :: Flag Bool,
845 846
      freezeTests            :: Flag Bool,
      freezeBenchmarks       :: Flag Bool,
847 848
      freezeSolver           :: Flag PreSolver,
      freezeMaxBackjumps     :: Flag Int,
849
      freezeReorderGoals     :: Flag ReorderGoals,
850
      freezeCountConflicts   :: Flag CountConflicts,
851 852 853
      freezeIndependentGoals :: Flag IndependentGoals,
      freezeShadowPkgs       :: Flag ShadowPkgs,
      freezeStrongFlags      :: Flag StrongFlags,
854
      freezeAllowBootLibInstalls :: Flag AllowBootLibInstalls,
855 856 857 858 859 860
      freezeVerbosity        :: Flag Verbosity
    }

defaultFreezeFlags :: FreezeFlags
defaultFreezeFlags = FreezeFlags {
    freezeDryRun           = toFlag False,
861 862
    freezeTests            = toFlag False,
    freezeBenchmarks       = toFlag False,
863 864
    freezeSolver           = Flag defaultSolver,
    freezeMaxBackjumps     = Flag defaultMaxBackjumps,
865
    freezeReorderGoals     = Flag (ReorderGoals False),
866
    freezeCountConflicts   = Flag (CountConflicts True),
867 868 869
    freezeIndependentGoals = Flag (IndependentGoals False),
    freezeShadowPkgs       = Flag (ShadowPkgs False),
    freezeStrongFlags      = Flag (StrongFlags False),
870
    freezeAllowBootLibInstalls = Flag (AllowBootLibInstalls False),
871 872 873 874 875 876 877
    freezeVerbosity        = toFlag normal
   }

freezeCommand :: CommandUI FreezeFlags
freezeCommand = CommandUI {
    commandName         = "freeze",
    commandSynopsis     = "Freeze dependencies.",
878 879 880 881 882 883 884 885
    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",
886
    commandNotes        = Nothing,
887
    commandUsage        = usageFlags "freeze",
888 889
    commandDefaultFlags = defaultFreezeFlags,
    commandOptions      = \ showOrParseArgs -> [
890 891