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

    , parsePackageArgs
38 39 40
    --TODO: stop exporting these:
    , showRepo
    , parseRepo
41 42
    ) where

43
import Distribution.Client.Types
44
         ( Username(..), Password(..), Repo(..), RemoteRepo(..), LocalRepo(..) )
45 46
import Distribution.Client.BuildReports.Types
         ( ReportLevel(..) )
47
import Distribution.Client.Dependency.Types
48
         ( AllowNewer(..), PreSolver(..) )
49 50
import qualified Distribution.Client.Init.Types as IT
         ( InitFlags(..), PackageType(..) )
51 52
import Distribution.Client.Targets
         ( UserConstraint, readUserConstraint )
53

54
import Distribution.Simple.Compiler (PackageDB)
55 56
import Distribution.Simple.Program
         ( defaultProgramConfiguration )
57
import Distribution.Simple.Command hiding (boolOpt)
Duncan Coutts's avatar
Duncan Coutts committed
58
import qualified Distribution.Simple.Setup as Cabal
59
import Distribution.Simple.Setup
60 61
         ( ConfigFlags(..), BuildFlags(..), TestFlags(..), BenchmarkFlags(..)
         , SDistFlags(..), HaddockFlags(..)
62
         , readPackageDbList, showPackageDbList
63
         , Flag(..), toFlag, fromFlag, flagToMaybe, flagToList
64
         , optionVerbosity, boolOpt, trueArg, falseArg, optionNumJobs )
65
import Distribution.Simple.InstallDirs
66 67
         ( PathTemplate, InstallDirs(sysconfdir)
         , toPathTemplate, fromPathTemplate )
68
import Distribution.Version
Duncan Coutts's avatar
Duncan Coutts committed
69
         ( Version(Version), anyVersion, thisVersion )
70
import Distribution.Package
71
         ( PackageIdentifier, packageName, packageVersion, Dependency(..) )
72 73
import Distribution.PackageDescription
         ( RepoKind(..) )
74
import Distribution.Text
75
         ( Text(..), display )
76
import Distribution.ReadE
77
         ( ReadE(..), readP_to_E, succeedReadE )
78
import qualified Distribution.Compat.ReadP as Parse
79
         ( ReadP, readP_to_S, readS_to_P, char, munch1, pfail, sepBy1, (+++) )
80 81
import Distribution.Verbosity
         ( Verbosity, normal )
82 83
import Distribution.Simple.Utils
         ( wrapText )
84

85 86
import Data.Char
         ( isSpace, isAlphaNum )
87 88
import Data.List
         ( intercalate )
89
import Data.Maybe
90
         ( listToMaybe, maybeToList, fromMaybe )
91 92 93 94 95 96 97 98
import Data.Monoid
         ( Monoid(..) )
import Control.Monad
         ( liftM )
import System.FilePath
         ( (</>) )
import Network.URI
         ( parseAbsoluteURI, uriToString )
99

100 101 102 103 104 105
-- ------------------------------------------------------------
-- * Global flags
-- ------------------------------------------------------------

-- | Flags that apply at the top level, not to any sub-command.
data GlobalFlags = GlobalFlags {
106 107 108 109 110 111 112 113 114
    globalVersion           :: Flag Bool,
    globalNumericVersion    :: Flag Bool,
    globalConfigFile        :: Flag FilePath,
    globalSandboxConfigFile :: Flag FilePath,
    globalRemoteRepos       :: [RemoteRepo],     -- ^ Available Hackage servers.
    globalCacheDir          :: Flag FilePath,
    globalLocalRepos        :: [FilePath],
    globalLogsDir           :: Flag FilePath,
    globalWorldFile         :: Flag FilePath
115
  }
Duncan Coutts's avatar
Duncan Coutts committed
116

117 118
defaultGlobalFlags :: GlobalFlags
defaultGlobalFlags  = GlobalFlags {
119 120 121 122 123 124 125 126 127
    globalVersion           = Flag False,
    globalNumericVersion    = Flag False,
    globalConfigFile        = mempty,
    globalSandboxConfigFile = mempty,
    globalRemoteRepos       = [],
    globalCacheDir          = mempty,
    globalLocalRepos        = mempty,
    globalLogsDir           = mempty,
    globalWorldFile         = mempty
128 129 130 131 132 133
  }

globalCommand :: CommandUI GlobalFlags
globalCommand = CommandUI {
    commandName         = "",
    commandSynopsis     = "",
134 135 136 137
    commandUsage        = \_ ->
         "This program is the command line interface "
           ++ "to the Haskell Cabal infrastructure.\n"
      ++ "See http://www.haskell.org/cabal/ for more information.\n",
138
    commandDescription  = Just $ \pname ->
139 140 141 142 143 144
         "For more information about a command use:\n"
      ++ "  " ++ pname ++ " COMMAND --help\n\n"
      ++ "To install Cabal packages from hackage use:\n"
      ++ "  " ++ pname ++ " install foo [--dry-run]\n\n"
      ++ "Occasionally you need to update the list of available packages:\n"
      ++ "  " ++ pname ++ " update\n",
145 146
    commandDefaultFlags = defaultGlobalFlags,
    commandOptions      = \showOrParseArgs ->
147
      (case showOrParseArgs of ShowArgs -> take 4; ParseArgs -> id)
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
      [option ['V'] ["version"]
         "Print version information"
         globalVersion (\v flags -> flags { globalVersion = v })
         trueArg

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

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

163 164 165 166 167 168
      ,option [] ["sandbox-config-file"]
         "Set an alternate location for the sandbox config file \
         \(default: './cabal.sandbox.config')"
         globalConfigFile (\v flags -> flags { globalSandboxConfigFile = v })
         (reqArgFlag "FILE")

169 170 171 172 173 174 175 176 177 178 179 180 181 182
      ,option [] ["remote-repo"]
         "The name and url for a remote repository"
         globalRemoteRepos (\v flags -> flags { globalRemoteRepos = v })
         (reqArg' "NAME:URL" (maybeToList . readRepo) (map showRepo))

      ,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 })
         (reqArg' "DIR" (\x -> [x]) id)
183

184 185 186 187 188
      ,option [] ["logs-dir"]
         "The location to put log files"
         globalLogsDir (\v flags -> flags { globalLogsDir = v })
         (reqArgFlag "DIR")

189 190 191 192
      ,option [] ["world-file"]
         "The location of the world file"
         globalWorldFile (\v flags -> flags { globalWorldFile = v })
         (reqArgFlag "FILE")
193 194 195 196 197
      ]
  }

instance Monoid GlobalFlags where
  mempty = GlobalFlags {
198 199 200 201 202 203 204 205 206
    globalVersion           = mempty,
    globalNumericVersion    = mempty,
    globalConfigFile        = mempty,
    globalSandboxConfigFile = mempty,
    globalRemoteRepos       = mempty,
    globalCacheDir          = mempty,
    globalLocalRepos        = mempty,
    globalLogsDir           = mempty,
    globalWorldFile         = mempty
207 208
  }
  mappend a b = GlobalFlags {
209 210 211 212 213 214 215 216 217
    globalVersion           = combine globalVersion,
    globalNumericVersion    = combine globalNumericVersion,
    globalConfigFile        = combine globalConfigFile,
    globalSandboxConfigFile = combine globalConfigFile,
    globalRemoteRepos       = combine globalRemoteRepos,
    globalCacheDir          = combine globalCacheDir,
    globalLocalRepos        = combine globalLocalRepos,
    globalLogsDir           = combine globalLogsDir,
    globalWorldFile         = combine globalWorldFile
Duncan Coutts's avatar
Duncan Coutts committed
218
  }
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
    where combine field = field a `mappend` field b

globalRepos :: GlobalFlags -> [Repo]
globalRepos globalFlags = remoteRepos ++ localRepos
  where
    remoteRepos =
      [ Repo (Left remote) cacheDir
      | remote <- globalRemoteRepos globalFlags
      , let cacheDir = fromFlag (globalCacheDir globalFlags)
                   </> remoteRepoName remote ]
    localRepos =
      [ Repo (Right LocalRepo) local
      | local <- globalLocalRepos globalFlags ]

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

237
configureCommand :: CommandUI ConfigFlags
238
configureCommand = (Cabal.configureCommand defaultProgramConfiguration) {
239
    commandDefaultFlags = mempty
Duncan Coutts's avatar
Duncan Coutts committed
240 241
  }

242 243 244
configureOptions ::  ShowOrParseArgs -> [OptionField ConfigFlags]
configureOptions = commandOptions configureCommand

245
filterConfigureFlags :: ConfigFlags -> Version -> ConfigFlags
246
filterConfigureFlags flags cabalLibVersion
247
  | cabalLibVersion >= Version [1,19,2] [] = flags_latest
248 249 250
  | cabalLibVersion <  Version [1,3,10] [] = flags_1_3_10
  | cabalLibVersion <  Version [1,10,0] [] = flags_1_10_0
  | cabalLibVersion <  Version [1,14,0] [] = flags_1_14_0
251
  | cabalLibVersion <  Version [1,18,0] [] = flags_1_18_0
252
  | cabalLibVersion <  Version [1,19,1] [] = flags_1_19_0
253
  | cabalLibVersion <  Version [1,19,2] [] = flags_1_19_1
254
  | otherwise = flags_latest
255
  where
256
    -- Cabal >= 1.19.1 uses '--dependency' and does not need '--constraint'.
257 258
    flags_latest = flags        { configConstraints = [] }

259 260 261 262 263
    -- Cabal < 1.19.2 doesn't know about '--exact-configuration'.
    flags_1_19_1 = flags_latest { configExactConfiguration = NoFlag }
    -- Cabal < 1.19.1 uses '--constraint' instead of '--dependency'.
    flags_1_19_0 = flags_1_19_1 { configDependencies = []
                                , configConstraints  = configConstraints flags }
264
    -- Cabal < 1.18.0 doesn't know about --extra-prog-path and --sysconfdir.
265
    flags_1_18_0 = flags_1_19_0 { configProgramPathExtra = []
266 267
                                , configInstallDirs = configInstallDirs_1_18_0}
    configInstallDirs_1_18_0 = (configInstallDirs flags) { sysconfdir = NoFlag }
268
    -- Cabal < 1.14.0 doesn't know about '--disable-benchmarks'.
269
    flags_1_14_0 = flags_1_18_0 { configBenchmarks  = NoFlag }
270
    -- Cabal < 1.10.0 doesn't know about '--disable-tests'.
271
    flags_1_10_0 = flags_1_14_0 { configTests       = NoFlag }
272
    -- Cabal < 1.3.10 does not grok the '--constraints' flag.
273
    flags_1_3_10 = flags_1_10_0 { configConstraints = [] }
274

275 276 277 278 279 280 281 282
-- ------------------------------------------------------------
-- * Config extra flags
-- ------------------------------------------------------------

-- | cabal configure takes some extra flags beyond runghc Setup configure
--
data ConfigExFlags = ConfigExFlags {
    configCabalVersion :: Flag Version,
283
    configExConstraints:: [UserConstraint],
284
    configPreferences  :: [Dependency],
285 286
    configSolver       :: Flag PreSolver,
    configAllowNewer   :: Flag AllowNewer
287 288 289
  }

defaultConfigExFlags :: ConfigExFlags
290 291
defaultConfigExFlags = mempty { configSolver     = Flag defaultSolver
                              , configAllowNewer = Flag AllowNewerNone }
292 293 294 295 296

configureExCommand :: CommandUI (ConfigFlags, ConfigExFlags)
configureExCommand = configureCommand {
    commandDefaultFlags = (mempty, defaultConfigExFlags),
    commandOptions      = \showOrParseArgs ->
297
         liftOptions fst setFst
298
         (filter ((`notElem` ["constraint", "dependency", "exact-configuration"])
299
                  . optionName) $ configureOptions  showOrParseArgs)
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
      ++ liftOptions snd setSnd (configureExOptions showOrParseArgs)
  }
  where
    setFst a (_,b) = (a,b)
    setSnd b (a,_) = (a,b)

configureExOptions ::  ShowOrParseArgs -> [OptionField ConfigExFlags]
configureExOptions _showOrParseArgs =
  [ 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))
315 316 317 318 319 320
  , option [] ["constraint"]
      "Specify constraints on a package (version, installed/source, flags)"
      configExConstraints (\v flags -> flags { configExConstraints = v })
      (reqArg "CONSTRAINT"
              (fmap (\x -> [x]) (ReadE readUserConstraint))
              (map display))
321 322 323 324

  , option [] ["preference"]
      "Specify preferences (soft constraints) on the version of a package"
      configPreferences (\v flags -> flags { configPreferences = v })
325 326 327 328
      (reqArg "CONSTRAINT"
              (readP_to_E (const "dependency expected")
                          (fmap (\x -> [x]) parse))
              (map display))
329 330

  , optionSolver configSolver (\v flags -> flags { configSolver = v })
331 332 333 334 335 336 337 338

  , option [] ["allow-newer"]
    "Ignore upper bounds in dependencies on some or all packages."
    configAllowNewer (\v flags -> flags { configAllowNewer = v})
    (optArg "PKGS"
     (fmap Flag allowNewerParser) (Flag AllowNewerAll)
     allowNewerPrinter)

339 340 341 342 343
  ]

instance Monoid ConfigExFlags where
  mempty = ConfigExFlags {
    configCabalVersion = mempty,
344
    configExConstraints= mempty,
345
    configPreferences  = mempty,
346 347
    configSolver       = mempty,
    configAllowNewer   = mempty
348 349 350
  }
  mappend a b = ConfigExFlags {
    configCabalVersion = combine configCabalVersion,
351
    configExConstraints= combine configExConstraints,
352
    configPreferences  = combine configPreferences,
353 354
    configSolver       = combine configSolver,
    configAllowNewer   = combine configAllowNewer
355 356 357
  }
    where combine field = field a `mappend` field b

ttuegel's avatar
ttuegel committed
358 359 360 361
-- ------------------------------------------------------------
-- * Build flags
-- ------------------------------------------------------------

362 363 364 365 366 367 368 369 370 371
data SkipAddSourceDepsCheck =
  SkipAddSourceDepsCheck | DontSkipAddSourceDepsCheck
  deriving Eq

data BuildExFlags = BuildExFlags {
  buildOnly     :: Flag SkipAddSourceDepsCheck
}

buildExOptions :: ShowOrParseArgs -> [OptionField BuildExFlags]
buildExOptions _showOrParseArgs =
372
  option [] ["only"]
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
  "Don't reinstall add-source dependencies (sandbox-only)"
  buildOnly (\v flags -> flags { buildOnly = v })
  (noArg (Flag SkipAddSourceDepsCheck))

  : []

buildCommand :: CommandUI (BuildFlags, BuildExFlags)
buildCommand = parent {
    commandDefaultFlags = (commandDefaultFlags parent, mempty),
    commandOptions      =
      \showOrParseArgs -> liftOptions fst setFst
                          (commandOptions parent showOrParseArgs)
                          ++
                          liftOptions snd setSnd (buildExOptions showOrParseArgs)
  }
  where
    setFst a (_,b) = (a,b)
    setSnd b (a,_) = (a,b)

    parent = Cabal.buildCommand defaultProgramConfiguration

instance Monoid BuildExFlags where
  mempty = BuildExFlags {
    buildOnly    = mempty
  }
  mappend a b = BuildExFlags {
    buildOnly    = combine buildOnly
  }
    where combine field = field a `mappend` field b

-- ------------------------------------------------------------
-- * Test command
-- ------------------------------------------------------------

407
testCommand :: CommandUI (TestFlags, BuildFlags, BuildExFlags)
408
testCommand = parent {
409 410
  commandDefaultFlags = (commandDefaultFlags parent,
                         Cabal.defaultBuildFlags, mempty),
411
  commandOptions      =
412
    \showOrParseArgs -> liftOptions get1 set1
413 414
                        (commandOptions parent showOrParseArgs)
                        ++
415 416 417 418
                        liftOptions get2 set2
                        (Cabal.buildOptions progConf showOrParseArgs)
                        ++
                        liftOptions get3 set3 (buildExOptions showOrParseArgs)
419 420
  }
  where
421 422 423
    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)
424

425 426
    parent   = Cabal.testCommand
    progConf = defaultProgramConfiguration
427 428 429 430 431

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

432
benchmarkCommand :: CommandUI (BenchmarkFlags, BuildFlags, BuildExFlags)
433
benchmarkCommand = parent {
434 435
  commandDefaultFlags = (commandDefaultFlags parent,
                         Cabal.defaultBuildFlags, mempty),
436
  commandOptions      =
437
    \showOrParseArgs -> liftOptions get1 set1
438 439
                        (commandOptions parent showOrParseArgs)
                        ++
440 441 442 443
                        liftOptions get2 set2
                        (Cabal.buildOptions progConf showOrParseArgs)
                        ++
                        liftOptions get3 set3 (buildExOptions showOrParseArgs)
ttuegel's avatar
ttuegel committed
444
  }
445
  where
446 447 448
    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)
449

450 451
    parent   = Cabal.benchmarkCommand
    progConf = defaultProgramConfiguration
ttuegel's avatar
ttuegel committed
452

453
-- ------------------------------------------------------------
454
-- * Fetch command
455
-- ------------------------------------------------------------
456

457 458 459 460
data FetchFlags = FetchFlags {
--    fetchOutput    :: Flag FilePath,
      fetchDeps      :: Flag Bool,
      fetchDryRun    :: Flag Bool,
461
      fetchSolver           :: Flag PreSolver,
462 463 464
      fetchMaxBackjumps     :: Flag Int,
      fetchReorderGoals     :: Flag Bool,
      fetchIndependentGoals :: Flag Bool,
465
      fetchShadowPkgs       :: Flag Bool,
466 467 468 469 470 471 472 473
      fetchVerbosity :: Flag Verbosity
    }

defaultFetchFlags :: FetchFlags
defaultFetchFlags = FetchFlags {
--  fetchOutput    = mempty,
    fetchDeps      = toFlag True,
    fetchDryRun    = toFlag False,
474 475 476 477
    fetchSolver           = Flag defaultSolver,
    fetchMaxBackjumps     = Flag defaultMaxBackjumps,
    fetchReorderGoals     = Flag False,
    fetchIndependentGoals = Flag False,
478
    fetchShadowPkgs       = Flag False,
479 480 481 482
    fetchVerbosity = toFlag normal
   }

fetchCommand :: CommandUI FetchFlags
Duncan Coutts's avatar
Duncan Coutts committed
483 484
fetchCommand = CommandUI {
    commandName         = "fetch",
485
    commandSynopsis     = "Downloads packages for later installation.",
Duncan Coutts's avatar
Duncan Coutts committed
486
    commandDescription  = Nothing,
refold's avatar
refold committed
487
    commandUsage        = usagePackages "fetch",
488
    commandDefaultFlags = defaultFetchFlags,
489
    commandOptions      = \ showOrParseArgs -> [
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
         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
511 512 513 514

       ] ++

       optionSolver      fetchSolver           (\v flags -> flags { fetchSolver           = v }) :
515 516
       optionSolverFlags showOrParseArgs
                         fetchMaxBackjumps     (\v flags -> flags { fetchMaxBackjumps     = v })
517 518
                         fetchReorderGoals     (\v flags -> flags { fetchReorderGoals     = v })
                         fetchIndependentGoals (\v flags -> flags { fetchIndependentGoals = v })
519
                         fetchShadowPkgs       (\v flags -> flags { fetchShadowPkgs       = v })
520

Duncan Coutts's avatar
Duncan Coutts committed
521 522
  }

523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
-- ------------------------------------------------------------
-- * Freeze command
-- ------------------------------------------------------------

data FreezeFlags = FreezeFlags {
      freezeDryRun           :: Flag Bool,
      freezeSolver           :: Flag PreSolver,
      freezeMaxBackjumps     :: Flag Int,
      freezeReorderGoals     :: Flag Bool,
      freezeIndependentGoals :: Flag Bool,
      freezeShadowPkgs       :: Flag Bool,
      freezeVerbosity        :: Flag Verbosity
    }

defaultFreezeFlags :: FreezeFlags
defaultFreezeFlags = FreezeFlags {
    freezeDryRun           = toFlag False,
    freezeSolver           = Flag defaultSolver,
    freezeMaxBackjumps     = Flag defaultMaxBackjumps,
    freezeReorderGoals     = Flag False,
    freezeIndependentGoals = Flag False,
    freezeShadowPkgs       = Flag False,
    freezeVerbosity        = toFlag normal
   }

freezeCommand :: CommandUI FreezeFlags
freezeCommand = CommandUI {
    commandName         = "freeze",
    commandSynopsis     = "Freeze dependencies.",
    commandDescription  = Nothing,
    commandUsage        = usagePackages "freeze",
    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

       ] ++

       optionSolver      freezeSolver           (\v flags -> flags { freezeSolver           = v }) :
       optionSolverFlags showOrParseArgs
                         freezeMaxBackjumps     (\v flags -> flags { freezeMaxBackjumps     = v })
                         freezeReorderGoals     (\v flags -> flags { freezeReorderGoals     = v })
                         freezeIndependentGoals (\v flags -> flags { freezeIndependentGoals = v })
                         freezeShadowPkgs       (\v flags -> flags { freezeShadowPkgs       = v })

  }

574 575 576 577
-- ------------------------------------------------------------
-- * Other commands
-- ------------------------------------------------------------

578
updateCommand  :: CommandUI (Flag Verbosity)
Duncan Coutts's avatar
Duncan Coutts committed
579 580
updateCommand = CommandUI {
    commandName         = "update",
581
    commandSynopsis     = "Updates list of known packages.",
Duncan Coutts's avatar
Duncan Coutts committed
582
    commandDescription  = Nothing,
refold's avatar
refold committed
583
    commandUsage        = usageFlags "update",
584
    commandDefaultFlags = toFlag normal,
585
    commandOptions      = \_ -> [optionVerbosity id const]
Duncan Coutts's avatar
Duncan Coutts committed
586 587
  }

588
upgradeCommand  :: CommandUI (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags)
589
upgradeCommand = configureCommand {
ijones's avatar
ijones committed
590
    commandName         = "upgrade",
591
    commandSynopsis     = "(command disabled, use install instead)",
ijones's avatar
ijones committed
592
    commandDescription  = Nothing,
refold's avatar
refold committed
593
    commandUsage        = usageFlagsOrPackages "upgrade",
594
    commandDefaultFlags = (mempty, mempty, mempty, mempty),
595
    commandOptions      = commandOptions installCommand
ijones's avatar
ijones committed
596 597
  }

Duncan Coutts's avatar
Duncan Coutts committed
598 599 600 601 602 603 604 605 606 607 608
{-
cleanCommand  :: CommandUI ()
cleanCommand = makeCommand name shortDesc longDesc emptyFlags options
  where
    name       = "clean"
    shortDesc  = "Removes downloaded files"
    longDesc   = Nothing
    emptyFlags = ()
    options _  = []
-}

609 610 611
checkCommand  :: CommandUI (Flag Verbosity)
checkCommand = CommandUI {
    commandName         = "check",
612
    commandSynopsis     = "Check the package for common mistakes.",
613 614
    commandDescription  = Nothing,
    commandUsage        = \pname -> "Usage: " ++ pname ++ " check\n",
615
    commandDefaultFlags = toFlag normal,
616
    commandOptions      = \_ -> []
617 618
  }

619
runCommand :: CommandUI (BuildFlags, BuildExFlags)
refold's avatar
refold committed
620 621 622 623 624
runCommand = CommandUI {
    commandName         = "run",
    commandSynopsis     = "Runs the compiled executable.",
    commandDescription  = Nothing,
    commandUsage        =
625 626 627
      \pname -> "Usage: " ++ pname
                ++ " run [FLAGS] [EXECUTABLE] [-- EXECUTABLE_FLAGS]\n\n"
                ++ "Flags for run:",
refold's avatar
refold committed
628
    commandDefaultFlags = mempty,
629 630 631 632 633 634
    commandOptions      =
      \showOrParseArgs -> liftOptions fst setFst
                          (Cabal.buildOptions progConf showOrParseArgs)
                          ++
                          liftOptions snd setSnd
                          (buildExOptions showOrParseArgs)
refold's avatar
refold committed
635 636
  }
  where
637 638 639
    setFst a (_,b) = (a,b)
    setSnd b (a,_) = (a,b)

refold's avatar
refold committed
640 641
    progConf = defaultProgramConfiguration

642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
-- ------------------------------------------------------------
-- * Report flags
-- ------------------------------------------------------------

data ReportFlags = ReportFlags {
    reportUsername  :: Flag Username,
    reportPassword  :: Flag Password,
    reportVerbosity :: Flag Verbosity
  }

defaultReportFlags :: ReportFlags
defaultReportFlags = ReportFlags {
    reportUsername  = mempty,
    reportPassword  = mempty,
    reportVerbosity = toFlag normal
  }

reportCommand :: CommandUI ReportFlags
660 661 662
reportCommand = CommandUI {
    commandName         = "report",
    commandSynopsis     = "Upload build reports to a remote server.",
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
    commandDescription  = Just $ \_ ->
         "You can store your Hackage login in the ~/.cabal/config file\n",
    commandUsage        = \pname -> "Usage: " ++ pname ++ " report [FLAGS]\n\n"
      ++ "Flags for upload:",
    commandDefaultFlags = defaultReportFlags,
    commandOptions      = \_ ->
      [optionVerbosity reportVerbosity (\v flags -> flags { reportVerbosity = v })

      ,option ['u'] ["username"]
        "Hackage username."
        reportUsername (\v flags -> flags { reportUsername = v })
        (reqArg' "USERNAME" (toFlag . Username)
                            (flagToList . fmap unUsername))

      ,option ['p'] ["password"]
        "Hackage password."
        reportPassword (\v flags -> flags { reportPassword = v })
        (reqArg' "PASSWORD" (toFlag . Password)
                            (flagToList . fmap unPassword))
      ]
683 684
  }

685 686 687 688 689 690 691 692 693 694 695 696 697
instance Monoid ReportFlags where
  mempty = ReportFlags {
    reportUsername  = mempty,
    reportPassword  = mempty,
    reportVerbosity = mempty
  }
  mappend a b = ReportFlags {
    reportUsername  = combine reportUsername,
    reportPassword  = combine reportPassword,
    reportVerbosity = combine reportVerbosity
  }
    where combine field = field a `mappend` field b

698
-- ------------------------------------------------------------
699
-- * Get flags
700 701
-- ------------------------------------------------------------

702 703 704 705 706 707
data GetFlags = GetFlags {
    getDestDir          :: Flag FilePath,
    getPristine         :: Flag Bool,
    getSourceRepository :: Flag (Maybe RepoKind),
    getVerbosity        :: Flag Verbosity
  }
708

709 710 711 712 713 714
defaultGetFlags :: GetFlags
defaultGetFlags = GetFlags {
    getDestDir          = mempty,
    getPristine         = mempty,
    getSourceRepository = mempty,
    getVerbosity        = toFlag normal
715 716
   }

717 718 719 720
getCommand :: CommandUI GetFlags
getCommand = CommandUI {
    commandName         = "get",
    commandSynopsis     = "Gets a package's source code.",
721 722 723 724 725
    commandDescription  = Just $ \_ ->
          "Creates a local copy of a package's source code. By default it gets "
       ++ "the source\ntarball and unpacks it in a local subdirectory. "
       ++ "Alternatively, with -s it will\nget the code from the source "
       ++ "repository specified by the package.\n",
726
    commandUsage        = usagePackages "get",
727 728
    commandDefaultFlags = mempty,
    commandOptions      = \_ -> [
729
        optionVerbosity getVerbosity (\v flags -> flags { getVerbosity = v })
730 731

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

736
       ,option "s" ["source-repository"]
737
         "Copy the package's source repository (ie git clone, darcs get, etc as appropriate)."
738 739 740 741 742 743
         getSourceRepository (\v flags -> flags { getSourceRepository = v })
        (optArg "[head|this|...]" (readP_to_E (const "invalid source-repository")
                                              (fmap (toFlag . Just) parse))
                                  (Flag Nothing)
                                  (map (fmap show) . flagToList))

744 745 746
       , option [] ["pristine"]
           ("Unpack the original pristine tarball, rather than updating the "
           ++ ".cabal file with the latest revision from the package archive.")
747
           getPristine (\v flags -> flags { getPristine = v })
748
           trueArg
749 750 751
       ]
  }

752 753 754 755 756 757 758
-- 'cabal unpack' is a deprecated alias for 'cabal get'.
unpackCommand :: CommandUI GetFlags
unpackCommand = getCommand {
  commandName  = "unpack",
  commandUsage = usagePackages "unpack"
  }

759 760 761 762 763 764 765
instance Monoid GetFlags where
  mempty = defaultGetFlags
  mappend a b = GetFlags {
    getDestDir          = combine getDestDir,
    getPristine         = combine getPristine,
    getSourceRepository = combine getSourceRepository,
    getVerbosity        = combine getVerbosity
766 767 768
  }
    where combine field = field a `mappend` field b

769 770 771 772 773
-- ------------------------------------------------------------
-- * List flags
-- ------------------------------------------------------------

data ListFlags = ListFlags {
774
    listInstalled    :: Flag Bool,
775
    listSimpleOutput :: Flag Bool,
776 777
    listVerbosity    :: Flag Verbosity,
    listPackageDBs   :: [Maybe PackageDB]
778 779 780 781
  }

defaultListFlags :: ListFlags
defaultListFlags = ListFlags {
782
    listInstalled    = Flag False,
783
    listSimpleOutput = Flag False,
784 785
    listVerbosity    = toFlag normal,
    listPackageDBs   = []
786 787 788 789 790
  }

listCommand  :: CommandUI ListFlags
listCommand = CommandUI {
    commandName         = "list",
791
    commandSynopsis     = "List packages matching a search string.",
792
    commandDescription  = Nothing,
refold's avatar
refold committed
793
    commandUsage        = usageFlagsOrPackages "list",
794
    commandDefaultFlags = defaultListFlags,
795
    commandOptions      = \_ -> [
796
        optionVerbosity listVerbosity (\v flags -> flags { listVerbosity = v })
797

798
        , option [] ["installed"]
799 800 801 802
            "Only print installed packages"
            listInstalled (\v flags -> flags { listInstalled = v })
            trueArg

803 804 805 806 807
        , option [] ["simple-output"]
            "Print in a easy-to-parse format"
            listSimpleOutput (\v flags -> flags { listSimpleOutput = v })
            trueArg

808 809 810 811 812
        , option "" ["package-db"]
          "Use a given package database. May be a specific file, 'global', 'user' or 'clear'."
          listPackageDBs (\v flags -> flags { listPackageDBs = v })
          (reqArg' "DB" readPackageDbList showPackageDbList)

813 814 815 816
        ]
  }

instance Monoid ListFlags where
817 818 819 820 821 822
  mempty = ListFlags {
    listInstalled    = mempty,
    listSimpleOutput = mempty,
    listVerbosity    = mempty,
    listPackageDBs   = mempty
    }
823
  mappend a b = ListFlags {
824
    listInstalled    = combine listInstalled,
825
    listSimpleOutput = combine listSimpleOutput,
826 827
    listVerbosity    = combine listVerbosity,
    listPackageDBs   = combine listPackageDBs
828 829 830
  }
    where combine field = field a `mappend` field b

831 832 833 834 835
-- ------------------------------------------------------------
-- * Info flags
-- ------------------------------------------------------------

data InfoFlags = InfoFlags {
836 837
    infoVerbosity  :: Flag Verbosity,
    infoPackageDBs :: [Maybe PackageDB]
838 839 840 841
  }

defaultInfoFlags :: InfoFlags
defaultInfoFlags = InfoFlags {
842 843
    infoVerbosity  = toFlag normal,
    infoPackageDBs = []
844 845 846 847 848 849 850
  }

infoCommand  :: CommandUI InfoFlags
infoCommand = CommandUI {
    commandName         = "info",
    commandSynopsis     = "Display detailed information about a particular package.",
    commandDescription  = Nothing,
refold's avatar
refold committed
851
    commandUsage        = usagePackages "info",
852 853 854
    commandDefaultFlags = defaultInfoFlags,
    commandOptions      = \_ -> [
        optionVerbosity infoVerbosity (\v flags -> flags { infoVerbosity = v })
855 856 857 858 859 860

        , option "" ["package-db"]
          "Use a given package database. May be a specific file, 'global', 'user' or 'clear'."
          infoPackageDBs (\v flags -> flags { infoPackageDBs = v })
          (reqArg' "DB" readPackageDbList showPackageDbList)

861 862 863 864
        ]
  }

instance Monoid InfoFlags where
865 866 867 868
  mempty = InfoFlags {
    infoVerbosity  = mempty,
    infoPackageDBs = mempty
    }
869
  mappend a b = InfoFlags {
870 871
    infoVerbosity  = combine infoVerbosity,
    infoPackageDBs = combine infoPackageDBs
872 873 874
  }
    where combine field = field a `mappend` field b

875 876 877 878
-- ------------------------------------------------------------
-- * Install flags
-- ------------------------------------------------------------

879 880
-- | Install takes the same flags as configure along with a few extras.
--
881
data InstallFlags = InstallFlags {
882 883 884
    installDocumentation    :: Flag Bool,
    installHaddockIndex     :: Flag PathTemplate,
    installDryRun           :: Flag Bool,
885 886 887
    installMaxBackjumps     :: Flag Int,
    installReorderGoals     :: Flag Bool,
    installIndependentGoals :: Flag Bool,
888
    installShadowPkgs       :: Flag Bool,
889 890
    installReinstall        :: Flag Bool,
    installAvoidReinstalls  :: Flag Bool,
891
    installOverrideReinstall :: Flag Bool,
892 893 894 895 896 897 898 899
    installUpgradeDeps      :: Flag Bool,
    installOnly             :: Flag Bool,
    installOnlyDeps         :: Flag Bool,
    installRootCmd          :: Flag String,
    installSummaryFile      :: [PathTemplate],
    installLogFile          :: Flag PathTemplate,
    installBuildReports     :: Flag ReportLevel,
    installSymlinkBinDir    :: Flag FilePath,
900
    installOneShot          :: Flag Bool,
901
    installNumJobs          :: Flag (Maybe Int)
902 903 904 905
  }

defaultInstallFlags :: InstallFlags
defaultInstallFlags = InstallFlags {
906 907 908
    installDocumentation   = Flag False,
    installHaddockIndex    = Flag docIndexFile,
    installDryRun          = Flag False,
909 910 911
    installMaxBackjumps    = Flag defaultMaxBackjumps,
    installReorderGoals    = Flag False,
    installIndependentGoals= Flag False,
912
    installShadowPkgs      = Flag False,
913 914
    installReinstall       = Flag False,
    installAvoidReinstalls = Flag False,
915
    installOverrideReinstall = Flag False,
916 917 918 919 920 921 922 923
    installUpgradeDeps     = Flag False,
    installOnly            = Flag False,
    installOnlyDeps        = Flag False,
    installRootCmd         = mempty,
    installSummaryFile     = mempty,
    installLogFile         = mempty,
    installBuildReports    = Flag NoReports,
    installSymlinkBinDir   = mempty,
924
    installOneShot         = Flag False,
925
    installNumJobs         = mempty
926
  }
927 928
  where
    docIndexFile = toPathTemplate ("$datadir" </> "doc" </> "index.html")
929

930 931 932 933 934 935 936 937 938 939 940 941 942
allowNewerParser :: ReadE AllowNewer
allowNewerParser = ReadE $ \s ->
  case s of
    ""      -> Right AllowNewerNone
    "False" -> Right AllowNewerNone
    "True"  -> Right AllowNewerAll
    _       ->
      case readPToMaybe pkgsParser s of
        Just pkgs -> Right . AllowNewerSome $ pkgs
        Nothing   -> Left ("Cannot parse the list of packages: " ++ s)
  where
    pkgsParser = Parse.sepBy1 parse (Parse.char ',')

943 944 945 946 947 948 949 950
allowNewerPrinter :: Flag AllowNewer -> [Maybe String]
allowNewerPrinter (Flag AllowNewerNone)        = [Just "False"]
allowNewerPrinter (Flag AllowNewerAll)         = [Just "True"]
allowNewerPrinter (Flag (AllowNewerSome pkgs)) =
  [Just . intercalate "," . map display $ pkgs]
allowNewerPrinter NoFlag                       = []


951 952 953
defaultMaxBackjumps :: Int
defaultMaxBackjumps = 200

954 955
defaultSolver :: PreSolver
defaultSolver = Choose
956 957

allSolvers :: String
958
allSolvers = intercalate ", " (map display ([minBound .. maxBound] :: [PreSolver]))
959

960
installCommand :: CommandUI (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags)
961
installCommand = CommandUI {
962 963
  commandName         = "install",
  commandSynopsis     = "Installs a list of packages.",
refold's avatar
refold committed
964
  commandUsage        = usageFlagsOrPackages "install",
965 966 967 968 969
  commandDescription  = Just $ \pname ->
    let original = case commandDescription configureCommand of
          Just desc -> desc pname ++ "\n"
          Nothing   -> ""
     in original
970
     ++ "Examples:\n"
971 972 973 974 975 976 977 978
     ++ "  " ++ pname ++ " install                 "
     ++ "    Package in the current directory\n"
     ++ "  " ++ pname ++ " install foo             "
     ++ "    Package from the hackage server\n"
     ++ "  " ++ pname ++ " install foo-1.0         "
     ++ "    Specific version of a package\n"
     ++ "  " ++ pname ++ " install 'foo < 2'       "
     ++ "    Constrained package version\n",
979
  commandDefaultFlags = (mempty, mempty, mempty, mempty),
980
  commandOptions      = \showOrParseArgs ->
981
       liftOptions get1 set1
982 983 984
       (filter ((`notElem` ["constraint", "dependency"
                           , "exact-configuration"])
                . optionName) $
985
                              configureOptions   showOrParseArgs)
986 987
    ++ liftOptions get2 set2 (configureExOptions showOrParseArgs)
    ++ liftOptions get3 set3 (installOptions     showOrParseArgs)
988
    ++ liftOptions get4 set4 (haddockOptions     showOrParseArgs)
989
  }
990
  where
991 992 993 994 995
    get1 (a,_,_,_) = a; set1 a (_,b,c,d) = (a,b,c,d)
    get2 (_,b,_,_) = b; set2 b (a,_,c,d) = (a,b,c,d)
    get3 (_,_,c,_) = c; set3 c (a,b,_,d) = (a,b,c,d)
    get4 (_,_,_,d) = d; set4 d (a,b,c,_) = (a,b,c,d)

996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
haddockOptions :: ShowOrParseArgs -> [OptionField HaddockFlags]
haddockOptions showOrParseArgs
  = [ opt { optionName = "haddock-" ++ name,
            optionDescr = [ fmapOptFlags (\(_, lflags) -> ([], map ("haddock-" ++) lflags)) descr
                          | descr <- optionDescr opt] }
    | opt <- commandOptions Cabal.haddockCommand showOrParseArgs
    , let name = optionName opt
    , name `elem` ["hoogle", "html", "html-location",
                   "executables", "internal", "css",
                   "hyperlink-source", "hscolour-css",
                   "contents-location"]
    ]
  where