Setup.hs 82.2 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(..), defaultGlobalFlags, globalRepos
15
    , configureCommand, ConfigFlags(..), filterConfigureFlags
16
17
    , configureExCommand, ConfigExFlags(..), defaultConfigExFlags
                        , configureExOptions
18
    , buildCommand, BuildFlags(..), BuildExFlags(..), SkipAddSourceDepsCheck(..)
19
    , replCommand, 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
    , formatCommand
30
    , uploadCommand, UploadFlags(..)
31
    , reportCommand, ReportFlags(..)
refold's avatar
refold committed
32
    , runCommand
33
    , initCommand, IT.InitFlags(..)
34
    , sdistCommand, SDistFlags(..), SDistExFlags(..), ArchiveFormat(..)
35
    , win32SelfUpgradeCommand, Win32SelfUpgradeFlags(..)
refold's avatar
refold committed
36
    , sandboxCommand, defaultSandboxLocation, SandboxFlags(..)
37
    , execCommand, ExecFlags(..)
38
    , userConfigCommand, UserConfigFlags(..)
Duncan Coutts's avatar
Duncan Coutts committed
39
40

    , parsePackageArgs
41
42
43
    --TODO: stop exporting these:
    , showRepo
    , parseRepo
44
45
    ) where

46
import Distribution.Client.Types
47
         ( Username(..), Password(..), Repo(..), RemoteRepo(..), LocalRepo(..) )
48
49
import Distribution.Client.BuildReports.Types
         ( ReportLevel(..) )
50
import Distribution.Client.Dependency.Types
51
         ( AllowNewer(..), PreSolver(..) )
52
53
import qualified Distribution.Client.Init.Types as IT
         ( InitFlags(..), PackageType(..) )
54
55
import Distribution.Client.Targets
         ( UserConstraint, readUserConstraint )
56
57
import Distribution.Utils.NubList
         ( NubList, toNubList, fromNubList)
58

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

92
93
import Data.Char
         ( isSpace, isAlphaNum )
94
import Data.List
95
         ( intercalate, deleteFirstsBy )
96
import Data.Maybe
97
         ( listToMaybe, maybeToList, fromMaybe )
98
99
100
101
102
103
104
105
import Data.Monoid
         ( Monoid(..) )
import Control.Monad
         ( liftM )
import System.FilePath
         ( (</>) )
import Network.URI
         ( parseAbsoluteURI, uriToString )
106

107
108
109
110
111
112
-- ------------------------------------------------------------
-- * Global flags
-- ------------------------------------------------------------

-- | Flags that apply at the top level, not to any sub-command.
data GlobalFlags = GlobalFlags {
113
114
115
116
    globalVersion           :: Flag Bool,
    globalNumericVersion    :: Flag Bool,
    globalConfigFile        :: Flag FilePath,
    globalSandboxConfigFile :: Flag FilePath,
117
    globalRemoteRepos       :: NubList RemoteRepo,     -- ^ Available Hackage servers.
118
    globalCacheDir          :: Flag FilePath,
119
    globalLocalRepos        :: NubList FilePath,
120
    globalLogsDir           :: Flag FilePath,
121
    globalWorldFile         :: Flag FilePath,
122
123
    globalRequireSandbox    :: Flag Bool,
    globalIgnoreSandbox     :: Flag Bool
124
  }
Duncan Coutts's avatar
Duncan Coutts committed
125

126
127
defaultGlobalFlags :: GlobalFlags
defaultGlobalFlags  = GlobalFlags {
128
129
130
131
    globalVersion           = Flag False,
    globalNumericVersion    = Flag False,
    globalConfigFile        = mempty,
    globalSandboxConfigFile = mempty,
132
    globalRemoteRepos       = mempty,
133
134
135
    globalCacheDir          = mempty,
    globalLocalRepos        = mempty,
    globalLogsDir           = mempty,
136
    globalWorldFile         = mempty,
137
138
    globalRequireSandbox    = Flag False,
    globalIgnoreSandbox     = Flag False
139
140
  }

141
142
globalCommand :: [Command action] -> CommandUI GlobalFlags
globalCommand commands = CommandUI {
143
    commandName         = "",
144
145
    commandSynopsis     =
         "Command line interface to the Haskell Cabal infrastructure.",
146
147
148
149
    commandUsage        = \pname ->
         "See http://www.haskell.org/cabal/ for more information.\n"
      ++ "\n"
      ++ "Usage: " ++ pname ++ " [GLOBAL FLAGS] [COMMAND [FLAGS]]\n",
150
    commandDescription  = Just $ \pname ->
151
152
153
      let
        commands' = commands ++ [commandAddAction helpCommandUI undefined]
        cmdDescs = getNormalCommandDescriptions commands'
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
        -- if new commands are added, we want them to appear even if they
        -- are not included in the custom listing below. Thus, we calculate
        -- the `otherCmds` list and append it under the `other` category.
        -- Alternatively, a new testcase could be added that ensures that
        -- the set of commands listed here is equal to the set of commands
        -- that are actually available.
        otherCmds = deleteFirstsBy (==) (map fst cmdDescs)
          [ "help"
          , "update"
          , "install"
          , "fetch"
          , "list"
          , "info"
          , "user-config"
          , "get"
          , "init"
          , "configure"
          , "build"
          , "clean"
          , "run"
          , "repl"
          , "test"
          , "bench"
          , "check"
          , "sdist"
          , "upload"
          , "report"
          , "freeze"
          , "haddock"
          , "hscolour"
          , "copy"
          , "register"
          , "sandbox"
          , "exec"
          ]
189
190
        maxlen    = maximum $ [length name | (name, _) <- cmdDescs]
        align str = str ++ replicate (maxlen - length str) ' '
191
192
193
194
195
196
197
198
199
        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
200
201
      in
         "Commands:\n"
202
203
204
205
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
236
237
238
239
240
241
242
      ++ unlines (
        [ startGroup "global"
        , addCmd "update"
        , addCmd "install"
        , par
        , addCmd "help"
        , addCmd "info"
        , addCmd "list"
        , addCmd "fetch"
        , addCmd "user-config"
        , par
        , startGroup "package"
        , addCmd "get"
        , addCmd "init"
        , par
        , addCmd "configure"
        , addCmd "build"
        , addCmd "clean"
        , par
        , addCmd "run"
        , addCmd "repl"
        , addCmd "test"
        , addCmd "bench"
        , par
        , addCmd "check"
        , addCmd "sdist"
        , addCmd "upload"
        , addCmd "report"
        , par
        , addCmd "freeze"
        , addCmd "haddock"
        , addCmd "hscolour"
        , addCmd "copy"
        , addCmd "register"
        , par
        , startGroup "sandbox"
        , addCmd "exec"
        , addCmdCustom "repl" "Open interpreter with access to sandbox packages."
        ] ++ if null otherCmds then [] else par
                                           :startGroup "other"
                                           :[addCmd n | n <- otherCmds])
243
244
      ++ "\n"
      ++ "For more information about a command use:\n"
245
246
      ++ "   " ++ pname ++ " COMMAND --help\n"
      ++ "or " ++ pname ++ " help COMMAND\n"
247
      ++ "\n"
248
      ++ "To install Cabal packages from hackage use:\n"
249
250
      ++ "  " ++ pname ++ " install foo [--dry-run]\n"
      ++ "\n"
251
252
      ++ "Occasionally you need to update the list of available packages:\n"
      ++ "  " ++ pname ++ " update\n",
253
    commandNotes = Nothing,
254
    commandDefaultFlags = mempty,
255
    commandOptions      = \showOrParseArgs ->
256
      (case showOrParseArgs of ShowArgs -> take 6; ParseArgs -> id)
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
      [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")

272
273
274
275
276
277
      ,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")

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

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

288
289
290
      ,option [] ["remote-repo"]
         "The name and url for a remote repository"
         globalRemoteRepos (\v flags -> flags { globalRemoteRepos = v })
291
         (reqArg' "NAME:URL" (toNubList . maybeToList . readRepo) (map showRepo . fromNubList))
292
293
294
295
296
297
298
299
300

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

303
304
305
306
307
      ,option [] ["logs-dir"]
         "The location to put log files"
         globalLogsDir (\v flags -> flags { globalLogsDir = v })
         (reqArgFlag "DIR")

308
309
310
311
      ,option [] ["world-file"]
         "The location of the world file"
         globalWorldFile (\v flags -> flags { globalWorldFile = v })
         (reqArgFlag "FILE")
312
313
314
315
316
      ]
  }

instance Monoid GlobalFlags where
  mempty = GlobalFlags {
317
318
319
320
321
322
323
324
    globalVersion           = mempty,
    globalNumericVersion    = mempty,
    globalConfigFile        = mempty,
    globalSandboxConfigFile = mempty,
    globalRemoteRepos       = mempty,
    globalCacheDir          = mempty,
    globalLocalRepos        = mempty,
    globalLogsDir           = mempty,
325
    globalWorldFile         = mempty,
326
327
    globalRequireSandbox    = mempty,
    globalIgnoreSandbox     = mempty
328
329
  }
  mappend a b = GlobalFlags {
330
331
332
333
334
335
336
337
    globalVersion           = combine globalVersion,
    globalNumericVersion    = combine globalNumericVersion,
    globalConfigFile        = combine globalConfigFile,
    globalSandboxConfigFile = combine globalConfigFile,
    globalRemoteRepos       = combine globalRemoteRepos,
    globalCacheDir          = combine globalCacheDir,
    globalLocalRepos        = combine globalLocalRepos,
    globalLogsDir           = combine globalLogsDir,
338
    globalWorldFile         = combine globalWorldFile,
339
340
    globalRequireSandbox    = combine globalRequireSandbox,
    globalIgnoreSandbox     = combine globalIgnoreSandbox
Duncan Coutts's avatar
Duncan Coutts committed
341
  }
342
343
344
345
346
347
348
    where combine field = field a `mappend` field b

globalRepos :: GlobalFlags -> [Repo]
globalRepos globalFlags = remoteRepos ++ localRepos
  where
    remoteRepos =
      [ Repo (Left remote) cacheDir
349
      | remote <- fromNubList $ globalRemoteRepos globalFlags
350
351
352
353
      , let cacheDir = fromFlag (globalCacheDir globalFlags)
                   </> remoteRepoName remote ]
    localRepos =
      [ Repo (Right LocalRepo) local
354
      | local <- fromNubList $ globalLocalRepos globalFlags ]
355
356
357
358

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

360
configureCommand :: CommandUI ConfigFlags
361
configureCommand = (Cabal.configureCommand defaultProgramConfiguration) {
362
    commandDefaultFlags = mempty
Duncan Coutts's avatar
Duncan Coutts committed
363
364
  }

365
366
367
configureOptions ::  ShowOrParseArgs -> [OptionField ConfigFlags]
configureOptions = commandOptions configureCommand

368
filterConfigureFlags :: ConfigFlags -> Version -> ConfigFlags
369
filterConfigureFlags flags cabalLibVersion
370
  | cabalLibVersion >= Version [1,19,2] [] = flags_latest
371
372
373
  | 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
374
  | cabalLibVersion <  Version [1,18,0] [] = flags_1_18_0
375
  | cabalLibVersion <  Version [1,19,1] [] = flags_1_19_0
376
  | cabalLibVersion <  Version [1,19,2] [] = flags_1_19_1
377
  | otherwise = flags_latest
378
  where
379
    -- Cabal >= 1.19.1 uses '--dependency' and does not need '--constraint'.
380
381
    flags_latest = flags        { configConstraints = [] }

382
383
384
385
386
    -- 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 }
387
    -- Cabal < 1.18.0 doesn't know about --extra-prog-path and --sysconfdir.
388
    flags_1_18_0 = flags_1_19_0 { configProgramPathExtra = toNubList []
389
390
                                , configInstallDirs = configInstallDirs_1_18_0}
    configInstallDirs_1_18_0 = (configInstallDirs flags) { sysconfdir = NoFlag }
391
    -- Cabal < 1.14.0 doesn't know about '--disable-benchmarks'.
392
    flags_1_14_0 = flags_1_18_0 { configBenchmarks  = NoFlag }
393
    -- Cabal < 1.10.0 doesn't know about '--disable-tests'.
394
    flags_1_10_0 = flags_1_14_0 { configTests       = NoFlag }
395
    -- Cabal < 1.3.10 does not grok the '--constraints' flag.
396
    flags_1_3_10 = flags_1_10_0 { configConstraints = [] }
397

398
399
400
401
402
403
404
405
-- ------------------------------------------------------------
-- * Config extra flags
-- ------------------------------------------------------------

-- | cabal configure takes some extra flags beyond runghc Setup configure
--
data ConfigExFlags = ConfigExFlags {
    configCabalVersion :: Flag Version,
406
    configExConstraints:: [UserConstraint],
407
    configPreferences  :: [Dependency],
408
409
    configSolver       :: Flag PreSolver,
    configAllowNewer   :: Flag AllowNewer
410
411
412
  }

defaultConfigExFlags :: ConfigExFlags
413
414
defaultConfigExFlags = mempty { configSolver     = Flag defaultSolver
                              , configAllowNewer = Flag AllowNewerNone }
415
416
417
418
419

configureExCommand :: CommandUI (ConfigFlags, ConfigExFlags)
configureExCommand = configureCommand {
    commandDefaultFlags = (mempty, defaultConfigExFlags),
    commandOptions      = \showOrParseArgs ->
420
         liftOptions fst setFst
421
         (filter ((`notElem` ["constraint", "dependency", "exact-configuration"])
422
                  . optionName) $ configureOptions  showOrParseArgs)
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
      ++ 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))
438
439
440
441
442
443
  , 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))
444
445
446
447

  , option [] ["preference"]
      "Specify preferences (soft constraints) on the version of a package"
      configPreferences (\v flags -> flags { configPreferences = v })
448
449
450
451
      (reqArg "CONSTRAINT"
              (readP_to_E (const "dependency expected")
                          (fmap (\x -> [x]) parse))
              (map display))
452
453

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

  , option [] ["allow-newer"]
cheecheeo's avatar
cheecheeo committed
456
    ("Ignore upper bounds in all dependencies or " ++ allowNewerArgument)
457
    configAllowNewer (\v flags -> flags { configAllowNewer = v})
cheecheeo's avatar
cheecheeo committed
458
    (optArg allowNewerArgument
459
460
461
     (fmap Flag allowNewerParser) (Flag AllowNewerAll)
     allowNewerPrinter)

462
  ]
cheecheeo's avatar
cheecheeo committed
463
  where allowNewerArgument = "DEPS"
464
465
466
467

instance Monoid ConfigExFlags where
  mempty = ConfigExFlags {
    configCabalVersion = mempty,
468
    configExConstraints= mempty,
469
    configPreferences  = mempty,
470
471
    configSolver       = mempty,
    configAllowNewer   = mempty
472
473
474
  }
  mappend a b = ConfigExFlags {
    configCabalVersion = combine configCabalVersion,
475
    configExConstraints= combine configExConstraints,
476
    configPreferences  = combine configPreferences,
477
478
    configSolver       = combine configSolver,
    configAllowNewer   = combine configAllowNewer
479
480
481
  }
    where combine field = field a `mappend` field b

ttuegel's avatar
ttuegel committed
482
483
484
485
-- ------------------------------------------------------------
-- * Build flags
-- ------------------------------------------------------------

486
487
488
489
490
491
492
493
494
495
data SkipAddSourceDepsCheck =
  SkipAddSourceDepsCheck | DontSkipAddSourceDepsCheck
  deriving Eq

data BuildExFlags = BuildExFlags {
  buildOnly     :: Flag SkipAddSourceDepsCheck
}

buildExOptions :: ShowOrParseArgs -> [OptionField BuildExFlags]
buildExOptions _showOrParseArgs =
496
  option [] ["only"]
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
  "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

-- ------------------------------------------------------------
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
-- * Repl command
-- ------------------------------------------------------------

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

    parent = Cabal.replCommand defaultProgramConfiguration

546
547
548
549
-- ------------------------------------------------------------
-- * Test command
-- ------------------------------------------------------------

550
testCommand :: CommandUI (TestFlags, BuildFlags, BuildExFlags)
551
testCommand = parent {
552
553
  commandDefaultFlags = (commandDefaultFlags parent,
                         Cabal.defaultBuildFlags, mempty),
554
  commandOptions      =
555
    \showOrParseArgs -> liftOptions get1 set1
556
557
                        (commandOptions parent showOrParseArgs)
                        ++
558
559
560
561
                        liftOptions get2 set2
                        (Cabal.buildOptions progConf showOrParseArgs)
                        ++
                        liftOptions get3 set3 (buildExOptions showOrParseArgs)
562
563
  }
  where
564
565
566
    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)
567

568
569
    parent   = Cabal.testCommand
    progConf = defaultProgramConfiguration
570
571
572
573
574

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

575
benchmarkCommand :: CommandUI (BenchmarkFlags, BuildFlags, BuildExFlags)
576
benchmarkCommand = parent {
577
578
  commandDefaultFlags = (commandDefaultFlags parent,
                         Cabal.defaultBuildFlags, mempty),
579
  commandOptions      =
580
    \showOrParseArgs -> liftOptions get1 set1
581
582
                        (commandOptions parent showOrParseArgs)
                        ++
583
584
585
586
                        liftOptions get2 set2
                        (Cabal.buildOptions progConf showOrParseArgs)
                        ++
                        liftOptions get3 set3 (buildExOptions showOrParseArgs)
ttuegel's avatar
ttuegel committed
587
  }
588
  where
589
590
591
    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)
592

593
594
    parent   = Cabal.benchmarkCommand
    progConf = defaultProgramConfiguration
ttuegel's avatar
ttuegel committed
595

596
-- ------------------------------------------------------------
597
-- * Fetch command
598
-- ------------------------------------------------------------
599

600
601
602
603
data FetchFlags = FetchFlags {
--    fetchOutput    :: Flag FilePath,
      fetchDeps      :: Flag Bool,
      fetchDryRun    :: Flag Bool,
604
      fetchSolver           :: Flag PreSolver,
605
606
607
      fetchMaxBackjumps     :: Flag Int,
      fetchReorderGoals     :: Flag Bool,
      fetchIndependentGoals :: Flag Bool,
608
      fetchShadowPkgs       :: Flag Bool,
Andres Löh's avatar
Andres Löh committed
609
      fetchStrongFlags      :: Flag Bool,
610
611
612
613
614
615
616
617
      fetchVerbosity :: Flag Verbosity
    }

defaultFetchFlags :: FetchFlags
defaultFetchFlags = FetchFlags {
--  fetchOutput    = mempty,
    fetchDeps      = toFlag True,
    fetchDryRun    = toFlag False,
618
619
    fetchSolver           = Flag defaultSolver,
    fetchMaxBackjumps     = Flag defaultMaxBackjumps,
620
    fetchReorderGoals     = Flag False,
621
    fetchIndependentGoals = Flag False,
622
    fetchShadowPkgs       = Flag False,
Andres Löh's avatar
Andres Löh committed
623
    fetchStrongFlags      = Flag False,
624
625
626
627
    fetchVerbosity = toFlag normal
   }

fetchCommand :: CommandUI FetchFlags
Duncan Coutts's avatar
Duncan Coutts committed
628
629
fetchCommand = CommandUI {
    commandName         = "fetch",
630
    commandSynopsis     = "Downloads packages for later installation.",
631
632
633
634
635
    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",
636
    commandNotes        = Nothing,
637
    commandDefaultFlags = defaultFetchFlags,
638
    commandOptions      = \ showOrParseArgs -> [
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
         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
660
661
662
663

       ] ++

       optionSolver      fetchSolver           (\v flags -> flags { fetchSolver           = v }) :
664
665
       optionSolverFlags showOrParseArgs
                         fetchMaxBackjumps     (\v flags -> flags { fetchMaxBackjumps     = v })
666
667
                         fetchReorderGoals     (\v flags -> flags { fetchReorderGoals     = v })
                         fetchIndependentGoals (\v flags -> flags { fetchIndependentGoals = v })
668
                         fetchShadowPkgs       (\v flags -> flags { fetchShadowPkgs       = v })
Andres Löh's avatar
Andres Löh committed
669
                         fetchStrongFlags      (\v flags -> flags { fetchStrongFlags      = v })
670

Duncan Coutts's avatar
Duncan Coutts committed
671
672
  }

673
674
675
676
677
678
-- ------------------------------------------------------------
-- * Freeze command
-- ------------------------------------------------------------

data FreezeFlags = FreezeFlags {
      freezeDryRun           :: Flag Bool,
679
680
      freezeTests            :: Flag Bool,
      freezeBenchmarks       :: Flag Bool,
681
682
683
684
685
      freezeSolver           :: Flag PreSolver,
      freezeMaxBackjumps     :: Flag Int,
      freezeReorderGoals     :: Flag Bool,
      freezeIndependentGoals :: Flag Bool,
      freezeShadowPkgs       :: Flag Bool,
Andres Löh's avatar
Andres Löh committed
686
      freezeStrongFlags      :: Flag Bool,
687
688
689
690
691
692
      freezeVerbosity        :: Flag Verbosity
    }

defaultFreezeFlags :: FreezeFlags
defaultFreezeFlags = FreezeFlags {
    freezeDryRun           = toFlag False,
693
694
    freezeTests            = toFlag False,
    freezeBenchmarks       = toFlag False,
695
696
    freezeSolver           = Flag defaultSolver,
    freezeMaxBackjumps     = Flag defaultMaxBackjumps,
697
    freezeReorderGoals     = Flag False,
698
699
    freezeIndependentGoals = Flag False,
    freezeShadowPkgs       = Flag False,
Andres Löh's avatar
Andres Löh committed
700
    freezeStrongFlags      = Flag False,
701
702
703
704
705
706
707
    freezeVerbosity        = toFlag normal
   }

freezeCommand :: CommandUI FreezeFlags
freezeCommand = CommandUI {
    commandName         = "freeze",
    commandSynopsis     = "Freeze dependencies.",
708
709
710
711
712
713
714
715
    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",
716
    commandNotes        = Nothing,
717
718
719
    commandUsage        = usageAlternatives "freeze" [""
                                                     ,"PACKAGES"
                                                     ],
720
721
722
723
724
725
726
727
728
    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

729
730
731
732
733
734
735
736
737
738
       , 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 [] [])

739
740
741
742
743
744
745
746
       ] ++

       optionSolver      freezeSolver           (\v flags -> flags { freezeSolver           = v }) :
       optionSolverFlags showOrParseArgs
                         freezeMaxBackjumps     (\v flags -> flags { freezeMaxBackjumps     = v })
                         freezeReorderGoals     (\v flags -> flags { freezeReorderGoals     = v })
                         freezeIndependentGoals (\v flags -> flags { freezeIndependentGoals = v })
                         freezeShadowPkgs       (\v flags -> flags { freezeShadowPkgs       = v })
Andres Löh's avatar
Andres Löh committed
747
                         freezeStrongFlags      (\v flags -> flags { freezeStrongFlags      = v })
748
749
750

  }

751
752
753
754
-- ------------------------------------------------------------
-- * Other commands
-- ------------------------------------------------------------

755
updateCommand  :: CommandUI (Flag Verbosity)
Duncan Coutts's avatar
Duncan Coutts committed
756
757
updateCommand = CommandUI {
    commandName         = "update",
758
    commandSynopsis     = "Updates list of known packages.",
759
760
761
    commandDescription  = Just $ \_ ->
      "For all known remote repositories, download the package list.\n",
    commandNotes        = Just $ \_ ->
762
763
764
      relevantConfigValuesText ["remote-repo"
                               ,"remote-repo-cache"
                               ,"local-repo"],
refold's avatar
refold committed
765
    commandUsage        = usageFlags "update",
766
    commandDefaultFlags = toFlag normal,
767
    commandOptions      = \_ -> [optionVerbosity id const]
Duncan Coutts's avatar
Duncan Coutts committed
768
769
  }

770
upgradeCommand  :: CommandUI (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags)
771
upgradeCommand = configureCommand {
ijones's avatar
ijones committed
772
    commandName         = "upgrade",
773
    commandSynopsis     = "(command disabled, use install instead)",
ijones's avatar
ijones committed
774
    commandDescription  = Nothing,
refold's avatar
refold committed
775
    commandUsage        = usageFlagsOrPackages "upgrade",
776
    commandDefaultFlags = (mempty, mempty, mempty, mempty),
777
    commandOptions      = commandOptions installCommand
ijones's avatar
ijones committed
778
779
  }

Duncan Coutts's avatar
Duncan Coutts committed
780
781
782
783
784
785
786
787
788
789
790
{-
cleanCommand  :: CommandUI ()
cleanCommand = makeCommand name shortDesc longDesc emptyFlags options
  where
    name       = "clean"
    shortDesc  = "Removes downloaded files"
    longDesc   = Nothing
    emptyFlags = ()
    options _  = []
-}

791
792
793
checkCommand  :: CommandUI (Flag Verbosity)
checkCommand = CommandUI {
    commandName         = "check",
794
    commandSynopsis     = "Check the package for common mistakes.",
795
796
797
798
799
800
    commandDescription  = Just $ \_ -> wrapText $
         "Expects a .cabal package file in the current directory.\n"
      ++ "\n"
      ++ "The checks correspond to the requirements to packages on Hackage. "
      ++ "If no errors and warnings are reported, Hackage will accept this "
      ++ "package.\n",
801
    commandNotes        = Nothing,
802
    commandUsage        = \pname -> "Usage: " ++ pname ++ " check\n",
803
    commandDefaultFlags = toFlag normal,
804
    commandOptions      = \_ -> []
805
806
  }

807
808
809
810
811
formatCommand  :: CommandUI (Flag Verbosity)
formatCommand = CommandUI {
    commandName         = "format",
    commandSynopsis     = "Reformat the .cabal file using the standard style.",
    commandDescription  = Nothing,
812
    commandNotes        = Nothing,
813
    commandUsage        = usageAlternatives "format" ["[FILE]"],
814
815
816
817
    commandDefaultFlags = toFlag normal,
    commandOptions      = \_ -> []
  }

818
runCommand :: CommandUI (BuildFlags, BuildExFlags)
refold's avatar
refold committed
819
820
runCommand = CommandUI {
    commandName         = "run",
821
822
823
824
825
    commandSynopsis     = "Builds and runs an executable.",
    commandDescription  = Just $ \_ -> wrapText $
         "Builds and then runs the specified executable. If no executable is "
      ++ "specified, but the package contains just one executable, that one "
      ++ "is built and executed.\n",
826
    commandNotes        = Nothing,
827
828
    commandUsage        = usageAlternatives "run"
        ["[FLAGS] [EXECUTABLE] [-- EXECUTABLE_FLAGS]"],
refold's avatar
refold committed
829
    commandDefaultFlags = mempty,
830
831
    commandOptions      =
      \showOrParseArgs -> liftOptions fst setFst
832
                          (commandOptions parent showOrParseArgs)
833
834
835
                          ++
                          liftOptions snd setSnd
                          (buildExOptions showOrParseArgs)
refold's avatar
refold committed
836
837
  }
  where
838
839
840
    setFst a (_,b) = (a,b)
    setSnd b (a,_) = (a,b)

841
    parent = Cabal.buildCommand defaultProgramConfiguration
refold's avatar
refold committed
842

843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
-- ------------------------------------------------------------
-- * 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
861
862
863
reportCommand = CommandUI {
    commandName         = "report",
    commandSynopsis     = "Upload build reports to a remote server.",
864
865
    commandDescription  = Nothing,
    commandNotes        = Just $ \_ ->
866
         "You can store your Hackage login in the ~/.cabal/config file\n",
867
    commandUsage        = usageAlternatives "report" ["[FLAGS]"],
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
    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))
      ]
884
885
  }

886
887
888
889
890
891
892
893
894
895
896
897
898
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

899
-- ------------------------------------------------------------
900
-- * Get flags
901
902
-- ------------------------------------------------------------

903
904
905
906
907
908
data GetFlags = GetFlags {
    getDestDir          :: Flag FilePath,
    getPristine         :: Flag Bool,
    getSourceRepository :: Flag (Maybe RepoKind),
    getVerbosity        :: Flag Verbosity
  }
909

910
911
912
913
914
915
defaultGetFlags :: GetFlags
defaultGetFlags = GetFlags {
    getDestDir          = mempty,
    getPristine         = mempty,
    getSourceRepository = mempty,
    getVerbosity        = toFlag normal
916
917
   }

918
919
920
getCommand :: CommandUI GetFlags
getCommand = CommandUI {
    commandName         = "get",
921
922
    commandSynopsis     = "Download/Extract a package's source code (repository).",
    commandDescription  = Just $ \_ -> wrapText $
923
924
925
926
          "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",
927
    commandNotes        = Nothing,
928
    commandUsage        = usagePackages "get",
929
    commandDefaultFlags = defaultGetFlags,
930
    commandOptions      = \_ -> [
931
        optionVerbosity getVerbosity (\v flags -> flags { getVerbosity = v })
932
933

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

938
       ,option "s" ["source-repository"]
939
         "Copy the package's source repository (ie git clone, darcs get, etc as appropriate)."
940
941
942
943
944
945
         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))

946
947
948
       , option [] ["pristine"]
           ("Unpack the original pristine tarball, rather than updating the "
           ++ ".cabal file with the latest revision from the package archive.")
949
           getPristine (\v flags -> flags { getPristine = v })
950
           trueArg
951
952
953
       ]
  }

954
955
956
957
958
959
960
-- 'cabal unpack' is a deprecated alias for 'cabal get'.
unpackCommand :: CommandUI GetFlags
unpackCommand = getCommand {
  commandName  = "unpack",
  commandUsage = usagePackages "unpack"
  }

961
instance Monoid GetFlags where
962
963
964
965
966
967
  mempty = GetFlags {
    getDestDir          = mempty,
    getPristine         = mempty,
    getSourceRepository = mempty,
    getVerbosity        = mempty
    }
968
969
970
971
972
  mappend a b = GetFlags {
    getDestDir          = combine getDestDir,
    getPristine         = combine getPristine,
    getSourceRepository = combine getSourceRepository,
    getVerbosity        = combine getVerbosity
973
974
975
  }
    where combine field = field a `mappend` field b

976
977
978
979
980
-- ------------------------------------------------------------
-- * List flags
-- ------------------------------------------------------------

data ListFlags = ListFlags {
981
    listInstalled    :: Flag Bool,
982
    listSimpleOutput :: Flag Bool,
983
984
    listVerbosity    :: Flag Verbosity,
    listPackageDBs   :: [Maybe PackageDB]
985
986
987
988
  }

defaultListFlags :: ListFlags
defaultListFlags = ListFlags {
989
    listInstalled    = Flag False,
990
    listSimpleOutput = Flag False,
991
992
    listVerbosity    = toFlag normal,
    listPackageDBs   = []
993
994
995
996
997
  }

listCommand  :: CommandUI ListFlags
listCommand = CommandUI {
    commandName         = "list",
998
    commandSynopsis     = "List packages matching a search string.",
999
1000
    commandDescription  = Just $ \_ -> wrapText $
         "List all packages, or all packages matching one of the search"