Setup.hs 90.2 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
    , getCommand, unpackCommand, GetFlags(..)
37
    , checkCommand
38
    , formatCommand
39
    , uploadCommand, UploadFlags(..), IsCandidate(..)
40
    , reportCommand, ReportFlags(..)
refold's avatar
refold committed
41
    , runCommand
42
    , initCommand, IT.InitFlags(..)
43
    , sdistCommand, SDistFlags(..), SDistExFlags(..), ArchiveFormat(..)
44
    , win32SelfUpgradeCommand, Win32SelfUpgradeFlags(..)
45
    , actAsSetupCommand, ActAsSetupFlags(..)
refold's avatar
refold committed
46
    , sandboxCommand, defaultSandboxLocation, SandboxFlags(..)
47
    , execCommand, ExecFlags(..)
48
    , userConfigCommand, UserConfigFlags(..)
Maciek Makowski's avatar
Maciek Makowski committed
49
    , manpageCommand
Duncan Coutts's avatar
Duncan Coutts committed
50 51

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

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

61
import Distribution.Client.Types
62
         ( Username(..), Password(..), RemoteRepo(..) )
63 64
import Distribution.Client.BuildReports.Types
         ( ReportLevel(..) )
65
import Distribution.Client.Dependency.Types
66
         ( PreSolver(..) )
67 68 69 70

import Distribution.Client.IndexUtils.Timestamp
         ( IndexState )

71 72
import qualified Distribution.Client.Init.Types as IT
         ( InitFlags(..), PackageType(..) )
73 74
import Distribution.Client.Targets
         ( UserConstraint, readUserConstraint )
75 76
import Distribution.Utils.NubList
         ( NubList, toNubList, fromNubList)
77

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

81 82
import Distribution.Simple.Compiler ( Compiler, PackageDB, PackageDBStack )
import Distribution.Simple.Program (ProgramDb, defaultProgramDb)
83 84
import Distribution.Simple.Command hiding (boolOpt, boolOpt')
import qualified Distribution.Simple.Command as Command
85
import Distribution.Simple.Configure
86
       ( configCompilerAuxEx, interpretPackageDbFlags, computeEffectiveProfiling )
Duncan Coutts's avatar
Duncan Coutts committed
87
import qualified Distribution.Simple.Setup as Cabal
88
import Distribution.Simple.Setup
89 90
         ( ConfigFlags(..), BuildFlags(..), ReplFlags
         , TestFlags(..), BenchmarkFlags(..)
91
         , SDistFlags(..), HaddockFlags(..)
92
         , readPackageDbList, showPackageDbList
Edsko de Vries's avatar
Edsko de Vries committed
93
         , Flag(..), toFlag, flagToMaybe, flagToList
94 95
         , BooleanFlag(..), optionVerbosity
         , boolOpt, boolOpt', trueArg, falseArg
96
         , readPToMaybe, optionNumJobs )
97
import Distribution.Simple.InstallDirs
98 99
         ( PathTemplate, InstallDirs(sysconfdir)
         , toPathTemplate, fromPathTemplate )
100
import Distribution.Version
Duncan Coutts's avatar
Duncan Coutts committed
101
         ( Version(Version), anyVersion, thisVersion )
102
import Distribution.Package
103
         ( PackageIdentifier, packageName, packageVersion, 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,  (+++) )
113
import Distribution.Verbosity
114
         ( Verbosity, lessVerbose, normal )
115
import Distribution.Simple.Utils
116
         ( wrapText, wrapLine )
117
import Distribution.Client.GlobalFlags
Edsko de Vries's avatar
Edsko de Vries committed
118 119 120
         ( GlobalFlags(..), defaultGlobalFlags
         , RepoContext(..), withRepoContext
         )
121

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

354 355 356 357 358 359 360 361
-- | 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.
362
filterConfigureFlags :: ConfigFlags -> Version -> ConfigFlags
363
filterConfigureFlags flags cabalLibVersion
364 365
  -- NB: we expect the latest version to be the most common case,
  -- so test it first.
366
  | cabalLibVersion >= Version [1,23,0] [] = flags_latest
367 368 369 370 371
  -- 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.
372 373
  | cabalLibVersion <  Version [1,3,10] [] = flags_1_3_10
  | cabalLibVersion <  Version [1,10,0] [] = flags_1_10_0
374
  | cabalLibVersion <  Version [1,12,0] [] = flags_1_12_0
375
  | cabalLibVersion <  Version [1,14,0] [] = flags_1_14_0
376
  | cabalLibVersion <  Version [1,18,0] [] = flags_1_18_0
377 378 379 380 381
  | cabalLibVersion <  Version [1,19,1] [] = flags_1_19_1
  | cabalLibVersion <  Version [1,19,2] [] = flags_1_19_2
  | cabalLibVersion <  Version [1,21,1] [] = flags_1_21_1
  | cabalLibVersion <  Version [1,22,0] [] = flags_1_22_0
  | cabalLibVersion <  Version [1,23,0] [] = flags_1_23_0
382
  | otherwise = flags_latest
383
  where
384 385 386
    flags_latest = flags        {
      -- Cabal >= 1.19.1 uses '--dependency' and does not need '--constraint'.
      configConstraints = [],
387
      -- Passing '--allow-{older,newer}' to Setup.hs is unnecessary, we use
388
      -- '--exact-configuration' instead.
389
      configAllowOlder  = Just (Cabal.AllowOlder Cabal.RelaxDepsNone),
390
      configAllowNewer  = Just (Cabal.AllowNewer Cabal.RelaxDepsNone)
391
      }
392

393
    -- Cabal < 1.23 doesn't know about '--profiling-detail'.
394 395 396
    -- Cabal < 1.23 has a hacked up version of 'enable-profiling'
    -- which we shouldn't use.
    (tryLibProfiling, tryExeProfiling) = computeEffectiveProfiling flags
397
    flags_1_23_0 = flags_latest { configProfDetail    = NoFlag
398
                                , configProfLibDetail = NoFlag
399 400 401 402 403
                                , configIPID          = NoFlag
                                , configProf = mempty
                                , configProfExe = Flag tryExeProfiling
                                , configProfLib = Flag tryLibProfiling
                                }
404

405
    -- Cabal < 1.22 doesn't know about '--disable-debug-info'.
406
    flags_1_22_0 = flags_1_23_0 { configDebugInfo = NoFlag }
407

408
    -- Cabal < 1.21.1 doesn't know about 'disable-relocatable'
409
    -- Cabal < 1.21.1 doesn't know about 'enable-profiling'
410
    -- (but we already dealt with it in flags_1_23_0)
411 412
    flags_1_21_1 =
      flags_1_22_0 { configRelocatable = NoFlag
413 414
                   , configCoverage = NoFlag
                   , configLibCoverage = configCoverage flags
415
                   }
416 417
    -- Cabal < 1.19.2 doesn't know about '--exact-configuration' and
    -- '--enable-library-stripping'.
418
    flags_1_19_2 = flags_1_21_1 { configExactConfiguration = NoFlag
419
                                , configStripLibs = NoFlag }
420
    -- Cabal < 1.19.1 uses '--constraint' instead of '--dependency'.
421
    flags_1_19_1 = flags_1_19_2 { configDependencies = []
422
                                , configConstraints  = configConstraints flags }
423
    -- Cabal < 1.18.0 doesn't know about --extra-prog-path and --sysconfdir.
424
    flags_1_18_0 = flags_1_19_1 { configProgramPathExtra = toNubList []
425 426
                                , configInstallDirs = configInstallDirs_1_18_0}
    configInstallDirs_1_18_0 = (configInstallDirs flags) { sysconfdir = NoFlag }
427
    -- Cabal < 1.14.0 doesn't know about '--disable-benchmarks'.
428
    flags_1_14_0 = flags_1_18_0 { configBenchmarks  = NoFlag }
429 430 431 432
    -- 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 }
433
    -- Cabal < 1.10.0 doesn't know about '--disable-tests'.
434
    flags_1_10_0 = flags_1_12_0 { configTests       = NoFlag }
435
    -- Cabal < 1.3.10 does not grok the '--constraints' flag.
436
    flags_1_3_10 = flags_1_10_0 { configConstraints = [] }
437

438 439
-- | Get the package database settings from 'ConfigFlags', accounting for
-- @--package-db@ and @--user@ flags.
440 441 442 443 444 445
configPackageDB' :: ConfigFlags -> PackageDBStack
configPackageDB' cfg =
    interpretPackageDbFlags userInstall (configPackageDBs cfg)
  where
    userInstall = Cabal.fromFlagOrDefault True (configUserInstall cfg)

446
-- | Configure the compiler, but reduce verbosity during this step.
447 448 449 450 451 452
configCompilerAux' :: ConfigFlags -> IO (Compiler, Platform, ProgramDb)
configCompilerAux' configFlags =
  configCompilerAuxEx configFlags
    --FIXME: make configCompilerAux use a sensible verbosity
    { configVerbosity = fmap lessVerbose (configVerbosity configFlags) }

453 454 455 456 457 458 459 460
-- ------------------------------------------------------------
-- * Config extra flags
-- ------------------------------------------------------------

-- | cabal configure takes some extra flags beyond runghc Setup configure
--
data ConfigExFlags = ConfigExFlags {
    configCabalVersion :: Flag Version,
461
    configExConstraints:: [(UserConstraint, ConstraintSource)],
462
    configPreferences  :: [Dependency],
463
    configSolver       :: Flag PreSolver
464
  }
465
  deriving (Eq, Generic)
466 467

defaultConfigExFlags :: ConfigExFlags
468
defaultConfigExFlags = mempty { configSolver     = Flag defaultSolver }
469 470 471 472 473

configureExCommand :: CommandUI (ConfigFlags, ConfigExFlags)
configureExCommand = configureCommand {
    commandDefaultFlags = (mempty, defaultConfigExFlags),
    commandOptions      = \showOrParseArgs ->
474
         liftOptions fst setFst
475
         (filter ((`notElem` ["constraint", "dependency", "exact-configuration"])
476
                  . optionName) $ configureOptions  showOrParseArgs)
477 478
      ++ liftOptions snd setSnd
         (configureExOptions showOrParseArgs ConstraintSourceCommandlineFlag)
479 480 481 482 483
  }
  where
    setFst a (_,b) = (a,b)
    setSnd b (a,_) = (a,b)

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

  , option [] ["preference"]
      "Specify preferences (soft constraints) on the version of a package"
      configPreferences (\v flags -> flags { configPreferences = v })
505 506 507 508
      (reqArg "CONSTRAINT"
              (readP_to_E (const "dependency expected")
                          (fmap (\x -> [x]) parse))
              (map display))
509 510

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

512 513 514
  ]

instance Monoid ConfigExFlags where
515
  mempty = gmempty
516 517 518
  mappend = (<>)

instance Semigroup ConfigExFlags where
519
  (<>) = gmappend
520

ttuegel's avatar
ttuegel committed
521 522 523 524 525 526
reconfigureCommand :: CommandUI (ConfigFlags, ConfigExFlags)
reconfigureCommand
  = configureExCommand
    { commandName         = "reconfigure"
    , commandSynopsis     = "Reconfigure the package if necessary."
    , commandDescription  = Just $ \pname -> wrapText $
527 528
         "Run `configure` with the most recently used flags, or append FLAGS "
         ++ "to the most recently used configuration. "
ttuegel's avatar
ttuegel committed
529
         ++ "Accepts the same flags as `" ++ pname ++ " configure'. "
530 531 532 533 534 535 536 537 538
         ++ "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
539 540 541 542
    , commandUsage        = usageAlternatives "reconfigure" [ "[FLAGS]" ]
    , commandDefaultFlags = mempty
    }

ttuegel's avatar
ttuegel committed
543 544 545 546
-- ------------------------------------------------------------
-- * Build flags
-- ------------------------------------------------------------

547 548 549 550 551 552
data SkipAddSourceDepsCheck =
  SkipAddSourceDepsCheck | DontSkipAddSourceDepsCheck
  deriving Eq

data BuildExFlags = BuildExFlags {
  buildOnly     :: Flag SkipAddSourceDepsCheck
553
} deriving Generic
554 555 556

buildExOptions :: ShowOrParseArgs -> [OptionField BuildExFlags]
buildExOptions _showOrParseArgs =
557
  option [] ["only"]
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
  "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)

577
    parent = Cabal.buildCommand defaultProgramDb
578 579

instance Monoid BuildExFlags where
580
  mempty = gmempty
581 582 583
  mappend = (<>)

instance Semigroup BuildExFlags where
584
  (<>) = gmappend
585 586

-- ------------------------------------------------------------
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
-- * 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)

603
    parent = Cabal.replCommand defaultProgramDb
604

605 606 607 608
-- ------------------------------------------------------------
-- * Test command
-- ------------------------------------------------------------

609
testCommand :: CommandUI (TestFlags, BuildFlags, BuildExFlags)
610
testCommand = parent {
611 612
  commandDefaultFlags = (commandDefaultFlags parent,
                         Cabal.defaultBuildFlags, mempty),
613
  commandOptions      =
614
    \showOrParseArgs -> liftOptions get1 set1
615 616
                        (commandOptions parent showOrParseArgs)
                        ++
617
                        liftOptions get2 set2
Mikhail Glushenkov's avatar
Mikhail Glushenkov committed
618
                        (Cabal.buildOptions progDb showOrParseArgs)
619 620
                        ++
                        liftOptions get3 set3 (buildExOptions showOrParseArgs)
621 622
  }
  where
623 624 625
    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)
626

Mikhail Glushenkov's avatar
Mikhail Glushenkov committed
627 628
    parent = Cabal.testCommand
    progDb = defaultProgramDb
629 630 631 632 633

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

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

Mikhail Glushenkov's avatar
Mikhail Glushenkov committed
652 653
    parent = Cabal.benchmarkCommand
    progDb = defaultProgramDb
ttuegel's avatar
ttuegel committed
654

655
-- ------------------------------------------------------------
656
-- * Fetch command
657
-- ------------------------------------------------------------
658

659 660 661 662
data FetchFlags = FetchFlags {
--    fetchOutput    :: Flag FilePath,
      fetchDeps      :: Flag Bool,
      fetchDryRun    :: Flag Bool,
663
      fetchSolver           :: Flag PreSolver,
664
      fetchMaxBackjumps     :: Flag Int,
665
      fetchReorderGoals     :: Flag ReorderGoals,
666
      fetchCountConflicts   :: Flag CountConflicts,
667 668 669
      fetchIndependentGoals :: Flag IndependentGoals,
      fetchShadowPkgs       :: Flag ShadowPkgs,
      fetchStrongFlags      :: Flag StrongFlags,
670 671 672 673 674 675 676 677
      fetchVerbosity :: Flag Verbosity
    }

defaultFetchFlags :: FetchFlags
defaultFetchFlags = FetchFlags {
--  fetchOutput    = mempty,
    fetchDeps      = toFlag True,
    fetchDryRun    = toFlag False,
678 679
    fetchSolver           = Flag defaultSolver,
    fetchMaxBackjumps     = Flag defaultMaxBackjumps,
680
    fetchReorderGoals     = Flag (ReorderGoals False),
681
    fetchCountConflicts   = Flag (CountConflicts True),
682 683 684
    fetchIndependentGoals = Flag (IndependentGoals False),
    fetchShadowPkgs       = Flag (ShadowPkgs False),
    fetchStrongFlags      = Flag (StrongFlags False),
685 686 687 688
    fetchVerbosity = toFlag normal
   }

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

       ] ++

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

Duncan Coutts's avatar
Duncan Coutts committed
733 734
  }

735 736 737 738 739 740
-- ------------------------------------------------------------
-- * Freeze command
-- ------------------------------------------------------------

data FreezeFlags = FreezeFlags {
      freezeDryRun           :: Flag Bool,
741 742
      freezeTests            :: Flag Bool,
      freezeBenchmarks       :: Flag Bool,
743 744
      freezeSolver           :: Flag PreSolver,
      freezeMaxBackjumps     :: Flag Int,
745
      freezeReorderGoals     :: Flag ReorderGoals,
746
      freezeCountConflicts   :: Flag CountConflicts,
747 748 749
      freezeIndependentGoals :: Flag IndependentGoals,
      freezeShadowPkgs       :: Flag ShadowPkgs,
      freezeStrongFlags      :: Flag StrongFlags,
750 751 752 753 754 755
      freezeVerbosity        :: Flag Verbosity
    }

defaultFreezeFlags :: FreezeFlags
defaultFreezeFlags = FreezeFlags {
    freezeDryRun           = toFlag False,
756 757
    freezeTests            = toFlag False,
    freezeBenchmarks       = toFlag False,
758 759
    freezeSolver           = Flag defaultSolver,
    freezeMaxBackjumps     = Flag defaultMaxBackjumps,
760
    freezeReorderGoals     = Flag (ReorderGoals False),
761
    freezeCountConflicts   = Flag (CountConflicts True),
762 763 764
    freezeIndependentGoals = Flag (IndependentGoals False),
    freezeShadowPkgs       = Flag (ShadowPkgs False),
    freezeStrongFlags      = Flag (StrongFlags 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
       ] ++

       optionSolver      freezeSolver           (\v flags -> flags { freezeSolver           = v }) :
       optionSolverFlags showOrParseArgs
                         freezeMaxBackjumps     (\v flags -> flags { freezeMaxBackjumps     = v })
                         freezeReorderGoals     (\v flags -> flags { freezeReorderGoals     = v })
807
                         freezeCountConflicts   (\v flags -> flags { freezeCountConflicts   = v })
808 809
                         freezeIndependentGoals (\v flags -> flags { freezeIndependentGoals = v })
                         freezeShadowPkgs       (\v flags -> flags { freezeShadowPkgs       = v })
Andres Löh's avatar
Andres Löh committed
810
                         freezeStrongFlags      (\v flags -> flags { freezeStrongFlags      = v })
811 812 813

  }

814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
genBoundsCommand :: CommandUI FreezeFlags
genBoundsCommand = CommandUI {
    commandName         = "gen-bounds",
    commandSynopsis     = "Generate dependency bounds.",
    commandDescription  = Just $ \_ -> wrapText $
         "Generates bounds for all dependencies that do not currently have them. "
      ++ "Generated bounds are printed to stdout.  You can then paste them into your .cabal file.\n"
      ++ "\n",
    commandNotes        = Nothing,
    commandUsage        = usageFlags "gen-bounds",
    commandDefaultFlags = defaultFreezeFlags,
    commandOptions      = \ _ -> [
     optionVerbosity freezeVerbosity (\v flags -> flags { freezeVerbosity = v })
     ]
  }

830 831 832 833
-- ------------------------------------------------------------
-- * Other commands
-- ------------------------------------------------------------

834
updateCommand  :: CommandUI (Flag Verbosity)
Duncan Coutts's avatar
Duncan Coutts committed
835 836
updateCommand = CommandUI {
    commandName         = "update",
837
    commandSynopsis     = "Updates list of known packages.",
838 839 840
    commandDescription  = Just $ \_ ->
      "For all known remote repositories, download the package list.\n",
    commandNotes        = Just $ \_ ->
841 842 843
      relevantConfigValuesText ["remote-repo"
                               ,"remote-repo-cache"
                               ,"local-repo"],
refold's avatar
refold committed
844
    commandUsage        = usageFlags "update",
845
    commandDefaultFlags = toFlag normal,
846
    commandOptions      = \_ -> [optionVerbosity id const]
Duncan Coutts's avatar
Duncan Coutts committed
847 848
  }

849
upgradeCommand  :: CommandUI (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags)
850
upgradeCommand = configureCommand {
ijones's avatar
ijones committed
851
    commandName         = "upgrade",
852
    commandSynopsis     = "(command disabled, use install instead)",
ijones's avatar
ijones committed
853
    commandDescription  = Nothing,
refold's avatar
refold committed
854
    commandUsage        = usageFlagsOrPackages "upgrade",
855
    commandDefaultFlags = (mempty, mempty, mempty, mempty),
856
    commandOptions      = commandOptions installCommand
ijones's avatar
ijones committed
857 858
  }

Duncan Coutts's avatar
Duncan Coutts committed
859 860 861 862 863 864 865 866 867 868 869
{-
cleanCommand  :: CommandUI ()
cleanCommand = makeCommand name shortDesc longDesc emptyFlags options
  where
    name       = "clean"
    shortDesc  = "Removes downloaded files"
    longDesc   = Nothing
<