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

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

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

-- | Flags that apply at the top level, not to any sub-command.
data GlobalFlags = GlobalFlags {
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,
115
116
    globalWorldFile         :: Flag FilePath,
    globalRequireSandbox    :: Flag Bool
117
  }
Duncan Coutts's avatar
Duncan Coutts committed
118

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

globalCommand :: CommandUI GlobalFlags
globalCommand = CommandUI {
    commandName         = "",
    commandSynopsis     = "",
137
138
139
140
    commandUsage        = \_ ->
         "This program is the command line interface "
           ++ "to the Haskell Cabal infrastructure.\n"
      ++ "See http://www.haskell.org/cabal/ for more information.\n",
141
    commandDescription  = Just $ \pname ->
142
143
144
145
146
147
         "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",
148
    commandDefaultFlags = mempty,
149
    commandOptions      = \showOrParseArgs ->
150
      (case showOrParseArgs of ShowArgs -> take 5; ParseArgs -> id)
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
      [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")

166
167
168
169
170
171
      ,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")

172
      ,option [] ["require-sandbox"]
Mikhail Glushenkov's avatar
Mikhail Glushenkov committed
173
         "requiring the presence of a sandbox for sandbox-aware commands"
174
175
176
         globalRequireSandbox (\v flags -> flags { globalRequireSandbox = v })
         (boolOpt' ([], ["require-sandbox"]) ([], ["no-require-sandbox"]))

177
178
179
180
181
182
183
184
185
186
187
188
189
190
      ,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)
191

192
193
194
195
196
      ,option [] ["logs-dir"]
         "The location to put log files"
         globalLogsDir (\v flags -> flags { globalLogsDir = v })
         (reqArgFlag "DIR")

197
198
199
200
      ,option [] ["world-file"]
         "The location of the world file"
         globalWorldFile (\v flags -> flags { globalWorldFile = v })
         (reqArgFlag "FILE")
201
202
203
204
205
      ]
  }

instance Monoid GlobalFlags where
  mempty = GlobalFlags {
206
207
208
209
210
211
212
213
    globalVersion           = mempty,
    globalNumericVersion    = mempty,
    globalConfigFile        = mempty,
    globalSandboxConfigFile = mempty,
    globalRemoteRepos       = mempty,
    globalCacheDir          = mempty,
    globalLocalRepos        = mempty,
    globalLogsDir           = mempty,
214
215
    globalWorldFile         = mempty,
    globalRequireSandbox    = mempty
216
217
  }
  mappend a b = GlobalFlags {
218
219
220
221
222
223
224
225
    globalVersion           = combine globalVersion,
    globalNumericVersion    = combine globalNumericVersion,
    globalConfigFile        = combine globalConfigFile,
    globalSandboxConfigFile = combine globalConfigFile,
    globalRemoteRepos       = combine globalRemoteRepos,
    globalCacheDir          = combine globalCacheDir,
    globalLocalRepos        = combine globalLocalRepos,
    globalLogsDir           = combine globalLogsDir,
226
227
    globalWorldFile         = combine globalWorldFile,
    globalRequireSandbox    = combine globalRequireSandbox
Duncan Coutts's avatar
Duncan Coutts committed
228
  }
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
    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
246

247
configureCommand :: CommandUI ConfigFlags
248
configureCommand = (Cabal.configureCommand defaultProgramConfiguration) {
249
    commandDefaultFlags = mempty
Duncan Coutts's avatar
Duncan Coutts committed
250
251
  }

252
253
254
configureOptions ::  ShowOrParseArgs -> [OptionField ConfigFlags]
configureOptions = commandOptions configureCommand

255
filterConfigureFlags :: ConfigFlags -> Version -> ConfigFlags
256
filterConfigureFlags flags cabalLibVersion
257
  | cabalLibVersion >= Version [1,19,2] [] = flags_latest
258
259
260
  | 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
261
  | cabalLibVersion <  Version [1,18,0] [] = flags_1_18_0
262
  | cabalLibVersion <  Version [1,19,1] [] = flags_1_19_0
263
  | cabalLibVersion <  Version [1,19,2] [] = flags_1_19_1
264
  | otherwise = flags_latest
265
  where
266
    -- Cabal >= 1.19.1 uses '--dependency' and does not need '--constraint'.
267
268
    flags_latest = flags        { configConstraints = [] }

269
270
271
272
273
    -- 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 }
274
    -- Cabal < 1.18.0 doesn't know about --extra-prog-path and --sysconfdir.
275
    flags_1_18_0 = flags_1_19_0 { configProgramPathExtra = []
276
277
                                , configInstallDirs = configInstallDirs_1_18_0}
    configInstallDirs_1_18_0 = (configInstallDirs flags) { sysconfdir = NoFlag }
278
    -- Cabal < 1.14.0 doesn't know about '--disable-benchmarks'.
279
    flags_1_14_0 = flags_1_18_0 { configBenchmarks  = NoFlag }
280
    -- Cabal < 1.10.0 doesn't know about '--disable-tests'.
281
    flags_1_10_0 = flags_1_14_0 { configTests       = NoFlag }
282
    -- Cabal < 1.3.10 does not grok the '--constraints' flag.
283
    flags_1_3_10 = flags_1_10_0 { configConstraints = [] }
284

285
286
287
288
289
290
291
292
-- ------------------------------------------------------------
-- * Config extra flags
-- ------------------------------------------------------------

-- | cabal configure takes some extra flags beyond runghc Setup configure
--
data ConfigExFlags = ConfigExFlags {
    configCabalVersion :: Flag Version,
293
    configExConstraints:: [UserConstraint],
294
    configPreferences  :: [Dependency],
295
296
    configSolver       :: Flag PreSolver,
    configAllowNewer   :: Flag AllowNewer
297
298
299
  }

defaultConfigExFlags :: ConfigExFlags
300
301
defaultConfigExFlags = mempty { configSolver     = Flag defaultSolver
                              , configAllowNewer = Flag AllowNewerNone }
302
303
304
305
306

configureExCommand :: CommandUI (ConfigFlags, ConfigExFlags)
configureExCommand = configureCommand {
    commandDefaultFlags = (mempty, defaultConfigExFlags),
    commandOptions      = \showOrParseArgs ->
307
         liftOptions fst setFst
308
         (filter ((`notElem` ["constraint", "dependency", "exact-configuration"])
309
                  . optionName) $ configureOptions  showOrParseArgs)
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
      ++ 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))
325
326
327
328
329
330
  , 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))
331
332
333
334

  , option [] ["preference"]
      "Specify preferences (soft constraints) on the version of a package"
      configPreferences (\v flags -> flags { configPreferences = v })
335
336
337
338
      (reqArg "CONSTRAINT"
              (readP_to_E (const "dependency expected")
                          (fmap (\x -> [x]) parse))
              (map display))
339
340

  , optionSolver configSolver (\v flags -> flags { configSolver = v })
341
342
343
344
345
346
347
348

  , 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)

349
350
351
352
353
  ]

instance Monoid ConfigExFlags where
  mempty = ConfigExFlags {
    configCabalVersion = mempty,
354
    configExConstraints= mempty,
355
    configPreferences  = mempty,
356
357
    configSolver       = mempty,
    configAllowNewer   = mempty
358
359
360
  }
  mappend a b = ConfigExFlags {
    configCabalVersion = combine configCabalVersion,
361
    configExConstraints= combine configExConstraints,
362
    configPreferences  = combine configPreferences,
363
364
    configSolver       = combine configSolver,
    configAllowNewer   = combine configAllowNewer
365
366
367
  }
    where combine field = field a `mappend` field b

ttuegel's avatar
ttuegel committed
368
369
370
371
-- ------------------------------------------------------------
-- * Build flags
-- ------------------------------------------------------------

372
373
374
375
376
377
378
379
380
381
data SkipAddSourceDepsCheck =
  SkipAddSourceDepsCheck | DontSkipAddSourceDepsCheck
  deriving Eq

data BuildExFlags = BuildExFlags {
  buildOnly     :: Flag SkipAddSourceDepsCheck
}

buildExOptions :: ShowOrParseArgs -> [OptionField BuildExFlags]
buildExOptions _showOrParseArgs =
382
  option [] ["only"]
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
  "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
-- ------------------------------------------------------------

417
testCommand :: CommandUI (TestFlags, BuildFlags, BuildExFlags)
418
testCommand = parent {
419
420
  commandDefaultFlags = (commandDefaultFlags parent,
                         Cabal.defaultBuildFlags, mempty),
421
  commandOptions      =
422
    \showOrParseArgs -> liftOptions get1 set1
423
424
                        (commandOptions parent showOrParseArgs)
                        ++
425
426
427
428
                        liftOptions get2 set2
                        (Cabal.buildOptions progConf showOrParseArgs)
                        ++
                        liftOptions get3 set3 (buildExOptions showOrParseArgs)
429
430
  }
  where
431
432
433
    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)
434

435
436
    parent   = Cabal.testCommand
    progConf = defaultProgramConfiguration
437
438
439
440
441

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

442
benchmarkCommand :: CommandUI (BenchmarkFlags, BuildFlags, BuildExFlags)
443
benchmarkCommand = parent {
444
445
  commandDefaultFlags = (commandDefaultFlags parent,
                         Cabal.defaultBuildFlags, mempty),
446
  commandOptions      =
447
    \showOrParseArgs -> liftOptions get1 set1
448
449
                        (commandOptions parent showOrParseArgs)
                        ++
450
451
452
453
                        liftOptions get2 set2
                        (Cabal.buildOptions progConf showOrParseArgs)
                        ++
                        liftOptions get3 set3 (buildExOptions showOrParseArgs)
ttuegel's avatar
ttuegel committed
454
  }
455
  where
456
457
458
    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)
459

460
461
    parent   = Cabal.benchmarkCommand
    progConf = defaultProgramConfiguration
ttuegel's avatar
ttuegel committed
462

463
-- ------------------------------------------------------------
464
-- * Fetch command
465
-- ------------------------------------------------------------
466

467
468
469
470
data FetchFlags = FetchFlags {
--    fetchOutput    :: Flag FilePath,
      fetchDeps      :: Flag Bool,
      fetchDryRun    :: Flag Bool,
471
      fetchSolver           :: Flag PreSolver,
472
473
474
      fetchMaxBackjumps     :: Flag Int,
      fetchReorderGoals     :: Flag Bool,
      fetchIndependentGoals :: Flag Bool,
475
      fetchShadowPkgs       :: Flag Bool,
476
477
478
479
480
481
482
483
      fetchVerbosity :: Flag Verbosity
    }

defaultFetchFlags :: FetchFlags
defaultFetchFlags = FetchFlags {
--  fetchOutput    = mempty,
    fetchDeps      = toFlag True,
    fetchDryRun    = toFlag False,
484
485
486
487
    fetchSolver           = Flag defaultSolver,
    fetchMaxBackjumps     = Flag defaultMaxBackjumps,
    fetchReorderGoals     = Flag False,
    fetchIndependentGoals = Flag False,
488
    fetchShadowPkgs       = Flag False,
489
490
491
492
    fetchVerbosity = toFlag normal
   }

fetchCommand :: CommandUI FetchFlags
Duncan Coutts's avatar
Duncan Coutts committed
493
494
fetchCommand = CommandUI {
    commandName         = "fetch",
495
    commandSynopsis     = "Downloads packages for later installation.",
Duncan Coutts's avatar
Duncan Coutts committed
496
    commandDescription  = Nothing,
refold's avatar
refold committed
497
    commandUsage        = usagePackages "fetch",
498
    commandDefaultFlags = defaultFetchFlags,
499
    commandOptions      = \ showOrParseArgs -> [
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
         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
521
522
523
524

       ] ++

       optionSolver      fetchSolver           (\v flags -> flags { fetchSolver           = v }) :
525
526
       optionSolverFlags showOrParseArgs
                         fetchMaxBackjumps     (\v flags -> flags { fetchMaxBackjumps     = v })
527
528
                         fetchReorderGoals     (\v flags -> flags { fetchReorderGoals     = v })
                         fetchIndependentGoals (\v flags -> flags { fetchIndependentGoals = v })
529
                         fetchShadowPkgs       (\v flags -> flags { fetchShadowPkgs       = v })
530

Duncan Coutts's avatar
Duncan Coutts committed
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
574
575
576
577
578
579
580
581
582
583
-- ------------------------------------------------------------
-- * 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 })

  }

584
585
586
587
-- ------------------------------------------------------------
-- * Other commands
-- ------------------------------------------------------------

588
updateCommand  :: CommandUI (Flag Verbosity)
Duncan Coutts's avatar
Duncan Coutts committed
589
590
updateCommand = CommandUI {
    commandName         = "update",
591
    commandSynopsis     = "Updates list of known packages.",
Duncan Coutts's avatar
Duncan Coutts committed
592
    commandDescription  = Nothing,
refold's avatar
refold committed
593
    commandUsage        = usageFlags "update",
594
    commandDefaultFlags = toFlag normal,
595
    commandOptions      = \_ -> [optionVerbosity id const]
Duncan Coutts's avatar
Duncan Coutts committed
596
597
  }

598
upgradeCommand  :: CommandUI (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags)
599
upgradeCommand = configureCommand {
ijones's avatar
ijones committed
600
    commandName         = "upgrade",
601
    commandSynopsis     = "(command disabled, use install instead)",
ijones's avatar
ijones committed
602
    commandDescription  = Nothing,
refold's avatar
refold committed
603
    commandUsage        = usageFlagsOrPackages "upgrade",
604
    commandDefaultFlags = (mempty, mempty, mempty, mempty),
605
    commandOptions      = commandOptions installCommand
ijones's avatar
ijones committed
606
607
  }

Duncan Coutts's avatar
Duncan Coutts committed
608
609
610
611
612
613
614
615
616
617
618
{-
cleanCommand  :: CommandUI ()
cleanCommand = makeCommand name shortDesc longDesc emptyFlags options
  where
    name       = "clean"
    shortDesc  = "Removes downloaded files"
    longDesc   = Nothing
    emptyFlags = ()
    options _  = []
-}

619
620
621
checkCommand  :: CommandUI (Flag Verbosity)
checkCommand = CommandUI {
    commandName         = "check",
622
    commandSynopsis     = "Check the package for common mistakes.",
623
624
    commandDescription  = Nothing,
    commandUsage        = \pname -> "Usage: " ++ pname ++ " check\n",
625
    commandDefaultFlags = toFlag normal,
626
    commandOptions      = \_ -> []
627
628
  }

629
runCommand :: CommandUI (BuildFlags, BuildExFlags)
refold's avatar
refold committed
630
631
632
633
634
runCommand = CommandUI {
    commandName         = "run",
    commandSynopsis     = "Runs the compiled executable.",
    commandDescription  = Nothing,
    commandUsage        =
635
636
637
      \pname -> "Usage: " ++ pname
                ++ " run [FLAGS] [EXECUTABLE] [-- EXECUTABLE_FLAGS]\n\n"
                ++ "Flags for run:",
refold's avatar
refold committed
638
    commandDefaultFlags = mempty,
639
640
641
642
643
644
    commandOptions      =
      \showOrParseArgs -> liftOptions fst setFst
                          (Cabal.buildOptions progConf showOrParseArgs)
                          ++
                          liftOptions snd setSnd
                          (buildExOptions showOrParseArgs)
refold's avatar
refold committed
645
646
  }
  where
647
648
649
    setFst a (_,b) = (a,b)
    setSnd b (a,_) = (a,b)

refold's avatar
refold committed
650
651
    progConf = defaultProgramConfiguration

652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
-- ------------------------------------------------------------
-- * 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
670
671
672
reportCommand = CommandUI {
    commandName         = "report",
    commandSynopsis     = "Upload build reports to a remote server.",
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
    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))
      ]
693
694
  }

695
696
697
698
699
700
701
702
703
704
705
706
707
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

708
-- ------------------------------------------------------------
709
-- * Get flags
710
711
-- ------------------------------------------------------------

712
713
714
715
716
717
data GetFlags = GetFlags {
    getDestDir          :: Flag FilePath,
    getPristine         :: Flag Bool,
    getSourceRepository :: Flag (Maybe RepoKind),
    getVerbosity        :: Flag Verbosity
  }
718

719
720
721
722
723
724
defaultGetFlags :: GetFlags
defaultGetFlags = GetFlags {
    getDestDir          = mempty,
    getPristine         = mempty,
    getSourceRepository = mempty,
    getVerbosity        = toFlag normal
725
726
   }

727
728
729
730
getCommand :: CommandUI GetFlags
getCommand = CommandUI {
    commandName         = "get",
    commandSynopsis     = "Gets a package's source code.",
731
732
733
734
735
    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",
736
    commandUsage        = usagePackages "get",
737
    commandDefaultFlags = defaultGetFlags,
738
    commandOptions      = \_ -> [
739
        optionVerbosity getVerbosity (\v flags -> flags { getVerbosity = v })
740
741

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

746
       ,option "s" ["source-repository"]
747
         "Copy the package's source repository (ie git clone, darcs get, etc as appropriate)."
748
749
750
751
752
753
         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))

754
755
756
       , option [] ["pristine"]
           ("Unpack the original pristine tarball, rather than updating the "
           ++ ".cabal file with the latest revision from the package archive.")
757
           getPristine (\v flags -> flags { getPristine = v })
758
           trueArg
759
760
761
       ]
  }

762
763
764
765
766
767
768
-- 'cabal unpack' is a deprecated alias for 'cabal get'.
unpackCommand :: CommandUI GetFlags
unpackCommand = getCommand {
  commandName  = "unpack",
  commandUsage = usagePackages "unpack"
  }

769
instance Monoid GetFlags where
770
771
772
773
774
775
  mempty = GetFlags {
    getDestDir          = mempty,
    getPristine         = mempty,
    getSourceRepository = mempty,
    getVerbosity        = mempty
    }
776
777
778
779
780
  mappend a b = GetFlags {
    getDestDir          = combine getDestDir,
    getPristine         = combine getPristine,
    getSourceRepository = combine getSourceRepository,
    getVerbosity        = combine getVerbosity
781
782
783
  }
    where combine field = field a `mappend` field b

784
785
786
787
788
-- ------------------------------------------------------------
-- * List flags
-- ------------------------------------------------------------

data ListFlags = ListFlags {
789
    listInstalled    :: Flag Bool,
790
    listSimpleOutput :: Flag Bool,
791
792
    listVerbosity    :: Flag Verbosity,
    listPackageDBs   :: [Maybe PackageDB]
793
794
795
796
  }

defaultListFlags :: ListFlags
defaultListFlags = ListFlags {
797
    listInstalled    = Flag False,
798
    listSimpleOutput = Flag False,
799
800
    listVerbosity    = toFlag normal,
    listPackageDBs   = []
801
802
803
804
805
  }

listCommand  :: CommandUI ListFlags
listCommand = CommandUI {
    commandName         = "list",
806
    commandSynopsis     = "List packages matching a search string.",
807
    commandDescription  = Nothing,
refold's avatar
refold committed
808
    commandUsage        = usageFlagsOrPackages "list",
809
    commandDefaultFlags = defaultListFlags,
810
    commandOptions      = \_ -> [
811
        optionVerbosity listVerbosity (\v flags -> flags { listVerbosity = v })
812

813
        , option [] ["installed"]
814
815
816
817
            "Only print installed packages"
            listInstalled (\v flags -> flags { listInstalled = v })
            trueArg

818
819
820
821
822
        , option [] ["simple-output"]
            "Print in a easy-to-parse format"
            listSimpleOutput (\v flags -> flags { listSimpleOutput = v })
            trueArg

823
824
825
826
827
        , 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)

828
829
830
831
        ]
  }

instance Monoid ListFlags where
832
833
834
835
836
837
  mempty = ListFlags {
    listInstalled    = mempty,
    listSimpleOutput = mempty,
    listVerbosity    = mempty,
    listPackageDBs   = mempty
    }
838
  mappend a b = ListFlags {
839
    listInstalled    = combine listInstalled,
840
    listSimpleOutput = combine listSimpleOutput,
841
842
    listVerbosity    = combine listVerbosity,
    listPackageDBs   = combine listPackageDBs
843
844
845
  }
    where combine field = field a `mappend` field b

846
847
848
849
850
-- ------------------------------------------------------------
-- * Info flags
-- ------------------------------------------------------------

data InfoFlags = InfoFlags {
851
852
    infoVerbosity  :: Flag Verbosity,
    infoPackageDBs :: [Maybe PackageDB]
853
854
855
856
  }

defaultInfoFlags :: InfoFlags
defaultInfoFlags = InfoFlags {
857
858
    infoVerbosity  = toFlag normal,
    infoPackageDBs = []
859
860
861
862
863
864
865
  }

infoCommand  :: CommandUI InfoFlags
infoCommand = CommandUI {
    commandName         = "info",
    commandSynopsis     = "Display detailed information about a particular package.",
    commandDescription  = Nothing,
refold's avatar
refold committed
866
    commandUsage        = usagePackages "info",
867
868
869
    commandDefaultFlags = defaultInfoFlags,
    commandOptions      = \_ -> [
        optionVerbosity infoVerbosity (\v flags -> flags { infoVerbosity = v })
870
871
872
873
874
875

        , 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)

876
877
878
879
        ]
  }

instance Monoid InfoFlags where
880
881
882
883
  mempty = InfoFlags {
    infoVerbosity  = mempty,
    infoPackageDBs = mempty
    }
884
  mappend a b = InfoFlags {
885
886
    infoVerbosity  = combine infoVerbosity,
    infoPackageDBs = combine infoPackageDBs
887
888
889
  }
    where combine field = field a `mappend` field b

890
891
892
893
-- ------------------------------------------------------------
-- * Install flags
-- ------------------------------------------------------------

894
895
-- | Install takes the same flags as configure along with a few extras.
--
896
data InstallFlags = InstallFlags {
897
898
899
    installDocumentation    :: Flag Bool,
    installHaddockIndex     :: Flag PathTemplate,
    installDryRun           :: Flag Bool,
900
901
902
    installMaxBackjumps     :: Flag Int,
    installReorderGoals     :: Flag Bool,
    installIndependentGoals :: Flag Bool,
903
    installShadowPkgs       :: Flag Bool,
904
905
    installReinstall        :: Flag Bool,
    installAvoidReinstalls  :: Flag Bool,
906
    installOverrideReinstall :: Flag Bool,
907
908
909
910
911
912
913
914
    installUpgradeDeps      :: Flag Bool,
    installOnly             :: Flag Bool,
    installOnlyDeps         :: Flag Bool,
    installRootCmd          :: Flag String,
    installSummaryFile      :: [PathTemplate],
    installLogFile          :: Flag PathTemplate,
    installBuildReports     :: Flag ReportLevel,
    installSymlinkBinDir    :: Flag FilePath,
915
    installOneShot          :: Flag Bool,
916
    installNumJobs          :: Flag (Maybe Int)
917
918
919
920
  }

defaultInstallFlags :: InstallFlags
defaultInstallFlags = InstallFlags {
921
922
923
    installDocumentation   = Flag False,
    installHaddockIndex    = Flag docIndexFile,
    installDryRun          = Flag False,
924
925
926
    installMaxBackjumps    = Flag defaultMaxBackjumps,
    installReorderGoals    = Flag False,
    installIndependentGoals= Flag False,
927
    installShadowPkgs      = Flag False,
928
929
    installReinstall       = Flag False,
    installAvoidReinstalls = Flag False,
930
    installOverrideReinstall = Flag False,
931
932
933
934
935
936
937
938
    installUpgradeDeps     = Flag False,
    installOnly            = Flag False,
    installOnlyDeps        = Flag False,
    installRootCmd         = mempty,
    installSummaryFile     = mempty,
    installLogFile         = mempty,
    installBuildReports    = Flag NoReports,
    installSymlinkBinDir   = mempty,
939
    installOneShot         = Flag False,
940
    installNumJobs         = mempty
941
  }
942
943
  where
    docIndexFile = toPathTemplate ("$datadir" </> "doc" </> "index.html")
944

945
946
947
948
949
950
951
952
953
954
955
956
957
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 ',')

958
959
960
961
962
963
964
965
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                       = []


966
967
968
defaultMaxBackjumps :: Int
defaultMaxBackjumps = 200

969
970
defaultSolver :: PreSolver
defaultSolver = Choose
971
972

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

975
installCommand :: CommandUI (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags)
976
installCommand = CommandUI {
977
978
  commandName         = "install",
  commandSynopsis     = "Installs a list of packages.",
refold's avatar
refold committed
979
  commandUsage        = usageFlagsOrPackages "install",
980
981
982
983
984
  commandDescription  = Just $ \pname ->
    let original = case commandDescription configureCommand of
          Just desc -> desc pname ++ "\n"
          Nothing   -> ""
     in original
985
     ++ "Examples:\n"
986
987
988
989
990
991
992
993
     ++ "  " ++ 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",
994
  commandDefaultFlags = (mempty, mempty, mempty, mempty),
995
  commandOptions      = \showOrParseArgs ->
996
       liftOptions get1 set1
997
998
999
       (filter ((`notElem` ["constraint", "dependency"
                           , "exact-configuration"])
                . optionName) $
1000
                              configureOptions   showOrParseArgs)