-
Notifications
You must be signed in to change notification settings - Fork 698
/
Install.hs
1587 lines (1391 loc) · 64.4 KB
/
Install.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
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
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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Client.Install
-- Copyright : (c) 2005 David Himmelstrup
-- 2007 Bjorn Bringert
-- 2007-2010 Duncan Coutts
-- License : BSD-like
--
-- Maintainer : cabal-devel@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- High level interface to package installation.
-----------------------------------------------------------------------------
module Distribution.Client.Install (
-- * High-level interface
install,
-- * Lower-level interface that allows to manipulate the install plan
makeInstallContext,
makeInstallPlan,
processInstallPlan,
InstallArgs,
InstallContext,
-- * Prune certain packages from the install plan
pruneInstallPlan
) where
import Prelude ()
import Distribution.Client.Compat.Prelude
import Distribution.Utils.Generic(safeLast)
import qualified Data.List.NonEmpty as NE
import qualified Data.Map as Map
import Control.Exception as Exception
( bracket, catches, Handler(Handler), handleJust )
import System.Directory
( getTemporaryDirectory, doesDirectoryExist, doesFileExist,
createDirectoryIfMissing, removeFile, renameDirectory,
getDirectoryContents )
import System.FilePath
( (</>), (<.>), equalFilePath, takeDirectory )
import System.IO
( openFile, IOMode(AppendMode), hClose )
import System.IO.Error
( isDoesNotExistError, ioeGetFileName )
import Distribution.Client.Targets
import Distribution.Client.Configure
( chooseCabalVersion, configureSetupScript, checkConfigExFlags )
import Distribution.Client.Dependency
import Distribution.Client.Dependency.Types
( Solver(..) )
import Distribution.Client.FetchUtils
import Distribution.Client.HttpUtils
( HttpTransport (..) )
import Distribution.Solver.Types.PackageFixedDeps
import qualified Distribution.Client.Haddock as Haddock (regenerateHaddockIndex)
import Distribution.Client.IndexUtils as IndexUtils
( getSourcePackagesAtIndexState, getInstalledPackages )
import qualified Distribution.Client.InstallPlan as InstallPlan
import qualified Distribution.Client.SolverInstallPlan as SolverInstallPlan
import Distribution.Client.InstallPlan (InstallPlan)
import Distribution.Client.SolverInstallPlan (SolverInstallPlan)
import Distribution.Client.Setup
( GlobalFlags(..), RepoContext(..)
, ConfigFlags(..), configureCommand, filterConfigureFlags
, ConfigExFlags(..), InstallFlags(..)
, filterTestFlags )
import Distribution.Client.Config
( getCabalDir, defaultUserInstall )
import Distribution.Client.Tar (extractTarGzFile)
import Distribution.Client.Types as Source
import Distribution.Client.BuildReports.Types
( ReportLevel(..) )
import Distribution.Client.SetupWrapper
( setupWrapper, SetupScriptOptions(..), defaultSetupScriptOptions )
import Distribution.Client.BuildReports.Anonymous (showBuildReport)
import qualified Distribution.Client.BuildReports.Anonymous as BuildReports
import qualified Distribution.Client.BuildReports.Storage as BuildReports
( storeAnonymous, storeLocal, fromInstallPlan, fromPlanningFailure )
import qualified Distribution.Client.InstallSymlink as InstallSymlink
( symlinkBinaries )
import Distribution.Client.Types.OverwritePolicy (OverwritePolicy (..))
import qualified Distribution.Client.Win32SelfUpgrade as Win32SelfUpgrade
import qualified Distribution.Client.World as World
import qualified Distribution.InstalledPackageInfo as Installed
import Distribution.Client.JobControl
import qualified Distribution.Solver.Types.ComponentDeps as CD
import Distribution.Solver.Types.ConstraintSource
import Distribution.Solver.Types.Settings
import Distribution.Solver.Types.LabeledPackageConstraint
import Distribution.Solver.Types.OptionalStanza
import qualified Distribution.Solver.Types.PackageIndex as SourcePackageIndex
import Distribution.Solver.Types.PkgConfigDb
( PkgConfigDb, readPkgConfigDb )
import Distribution.Solver.Types.SourcePackage as SourcePackage
import Distribution.Utils.NubList
import Distribution.Simple.Compiler
( CompilerId(..), Compiler(compilerId), compilerFlavor
, CompilerInfo(..), compilerInfo, PackageDB(..), PackageDBStack )
import Distribution.Simple.Program (ProgramDb)
import qualified Distribution.Simple.InstallDirs as InstallDirs
import qualified Distribution.Simple.PackageIndex as PackageIndex
import Distribution.Simple.PackageIndex (InstalledPackageIndex)
import Distribution.Simple.Setup
( haddockCommand, HaddockFlags(..)
, buildCommand, BuildFlags(..), emptyBuildFlags
, TestFlags, BenchmarkFlags
, toFlag, fromFlag, fromFlagOrDefault, flagToMaybe, defaultDistPref )
import qualified Distribution.Simple.Setup as Cabal
( Flag(..)
, copyCommand, CopyFlags(..), emptyCopyFlags
, registerCommand, RegisterFlags(..), emptyRegisterFlags
, testCommand, TestFlags(..) )
import Distribution.Simple.Utils
( createDirectoryIfMissingVerbose, writeFileAtomic )
import Distribution.Simple.InstallDirs as InstallDirs
( PathTemplate, fromPathTemplate, toPathTemplate, substPathTemplate
, initialPathTemplateEnv, installDirsTemplateEnv )
import Distribution.Simple.Configure (interpretPackageDbFlags)
import Distribution.Simple.Register (registerPackage, defaultRegisterOptions)
import Distribution.Package
( PackageIdentifier(..), PackageId, packageName, packageVersion
, Package(..), HasMungedPackageId(..), HasUnitId(..)
, UnitId )
import Distribution.Types.Dependency
( Dependency (..), mainLibSet )
import Distribution.Types.GivenComponent
( GivenComponent(..) )
import Distribution.Types.PackageVersionConstraint
( PackageVersionConstraint(..), thisPackageVersionConstraint )
import Distribution.Types.MungedPackageId
import qualified Distribution.PackageDescription as PackageDescription
import Distribution.PackageDescription
( PackageDescription, GenericPackageDescription(..), PackageFlag(..)
, FlagAssignment, mkFlagAssignment, unFlagAssignment
, showFlagValue, diffFlagAssignment, nullFlagAssignment )
import Distribution.PackageDescription.Configuration
( finalizePD )
import Distribution.Version
( Version, VersionRange, foldVersionRange )
import Distribution.Simple.Utils as Utils
( notice, info, warn, debug, debugNoWrap, die'
, withTempDirectory )
import Distribution.Client.Utils
( determineNumJobs, logDirChange, mergeBy, MergeResult(..)
, ProgressPhase(..), progressMessage )
import Distribution.System
( Platform, OS(Windows), buildOS, buildPlatform )
import Distribution.Verbosity as Verbosity
( modifyVerbosity, normal, verbose )
import Distribution.Simple.BuildPaths ( exeExtension )
import qualified Data.ByteString as BS
--TODO:
-- * assign flags to packages individually
-- * complain about flags that do not apply to any package given as target
-- so flags do not apply to dependencies, only listed, can use flag
-- constraints for dependencies
-- * only record applicable flags in world file
-- * allow flag constraints
-- * allow installed constraints
-- * allow flag and installed preferences
-- * change world file to use cabal section syntax
-- * allow persistent configure flags for each package individually
-- ------------------------------------------------------------
-- * Top level user actions
-- ------------------------------------------------------------
-- | Installs the packages needed to satisfy a list of dependencies.
--
install
:: Verbosity
-> PackageDBStack
-> RepoContext
-> Compiler
-> Platform
-> ProgramDb
-> GlobalFlags
-> ConfigFlags
-> ConfigExFlags
-> InstallFlags
-> HaddockFlags
-> TestFlags
-> BenchmarkFlags
-> [UserTarget]
-> IO ()
install verbosity packageDBs repos comp platform progdb
globalFlags configFlags configExFlags installFlags
haddockFlags testFlags benchmarkFlags userTargets0 = do
unless (installRootCmd installFlags == Cabal.NoFlag) $
warn verbosity $ "--root-cmd is no longer supported, "
++ "see https://github.com/haskell/cabal/issues/3353"
++ " (if you didn't type --root-cmd, comment out root-cmd"
++ " in your ~/.cabal/config file)"
let userOrSandbox = fromFlag (configUserInstall configFlags)
unless userOrSandbox $
warn verbosity $ "the --global flag is deprecated -- "
++ "it is generally considered a bad idea to install packages "
++ "into the global store"
installContext <- makeInstallContext verbosity args (Just userTargets0)
planResult <- foldProgress logMsg (return . Left) (return . Right) =<<
makeInstallPlan verbosity args installContext
case planResult of
Left message -> do
reportPlanningFailure verbosity args installContext message
die'' message
Right installPlan ->
processInstallPlan verbosity args installContext installPlan
where
args :: InstallArgs
args = (packageDBs, repos, comp, platform, progdb,
globalFlags, configFlags, configExFlags,
installFlags, haddockFlags, testFlags, benchmarkFlags)
die'' = die' verbosity
logMsg message rest = debugNoWrap verbosity message >> rest
-- TODO: Make InstallContext a proper data type with documented fields.
-- | Common context for makeInstallPlan and processInstallPlan.
type InstallContext = ( InstalledPackageIndex, SourcePackageDb
, PkgConfigDb
, [UserTarget], [PackageSpecifier UnresolvedSourcePackage]
, HttpTransport )
-- TODO: Make InstallArgs a proper data type with documented fields or just get
-- rid of it completely.
-- | Initial arguments given to 'install' or 'makeInstallContext'.
type InstallArgs = ( PackageDBStack
, RepoContext
, Compiler
, Platform
, ProgramDb
, GlobalFlags
, ConfigFlags
, ConfigExFlags
, InstallFlags
, HaddockFlags
, TestFlags
, BenchmarkFlags )
-- | Make an install context given install arguments.
makeInstallContext :: Verbosity -> InstallArgs -> Maybe [UserTarget]
-> IO InstallContext
makeInstallContext verbosity
(packageDBs, repoCtxt, comp, _, progdb,
globalFlags, _, configExFlags, installFlags, _, _, _) mUserTargets = do
let idxState = flagToMaybe (installIndexState installFlags)
installedPkgIndex <- getInstalledPackages verbosity comp packageDBs progdb
(sourcePkgDb, _) <- getSourcePackagesAtIndexState verbosity repoCtxt idxState Nothing
pkgConfigDb <- readPkgConfigDb verbosity progdb
checkConfigExFlags verbosity installedPkgIndex
(packageIndex sourcePkgDb) configExFlags
transport <- repoContextGetTransport repoCtxt
(userTargets, pkgSpecifiers) <- case mUserTargets of
Nothing ->
-- We want to distinguish between the case where the user has given an
-- empty list of targets on the command-line and the case where we
-- specifically want to have an empty list of targets.
return ([], [])
Just userTargets0 -> do
-- For install, if no target is given it means we use the current
-- directory as the single target.
let userTargets | null userTargets0 = [UserTargetLocalDir "."]
| otherwise = userTargets0
pkgSpecifiers <- resolveUserTargets verbosity repoCtxt
(fromFlag $ globalWorldFile globalFlags)
(packageIndex sourcePkgDb)
userTargets
return (userTargets, pkgSpecifiers)
return (installedPkgIndex, sourcePkgDb, pkgConfigDb, userTargets
,pkgSpecifiers, transport)
-- | Make an install plan given install context and install arguments.
makeInstallPlan :: Verbosity -> InstallArgs -> InstallContext
-> IO (Progress String String SolverInstallPlan)
makeInstallPlan verbosity
(_, _, comp, platform,_,
_, configFlags, configExFlags, installFlags,
_, _, _)
(installedPkgIndex, sourcePkgDb, pkgConfigDb,
_, pkgSpecifiers, _) = do
solver <- chooseSolver verbosity (fromFlag (configSolver configExFlags))
(compilerInfo comp)
notice verbosity "Resolving dependencies..."
return $ planPackages verbosity comp platform solver
configFlags configExFlags installFlags
installedPkgIndex sourcePkgDb pkgConfigDb pkgSpecifiers
-- | Given an install plan, perform the actual installations.
processInstallPlan :: Verbosity -> InstallArgs -> InstallContext
-> SolverInstallPlan
-> IO ()
processInstallPlan verbosity
args@(_,_, _, _, _, _, configFlags, _, installFlags, _, _, _)
(installedPkgIndex, sourcePkgDb, _,
userTargets, pkgSpecifiers, _) installPlan0 = do
checkPrintPlan verbosity installedPkgIndex installPlan sourcePkgDb
installFlags pkgSpecifiers
unless (dryRun || nothingToInstall) $ do
buildOutcomes <- performInstallations verbosity
args installedPkgIndex installPlan
postInstallActions verbosity args userTargets installPlan buildOutcomes
where
installPlan = InstallPlan.configureInstallPlan configFlags installPlan0
dryRun = fromFlag (installDryRun installFlags)
nothingToInstall = null (fst (InstallPlan.ready installPlan))
-- ------------------------------------------------------------
-- * Installation planning
-- ------------------------------------------------------------
planPackages :: Verbosity
-> Compiler
-> Platform
-> Solver
-> ConfigFlags
-> ConfigExFlags
-> InstallFlags
-> InstalledPackageIndex
-> SourcePackageDb
-> PkgConfigDb
-> [PackageSpecifier UnresolvedSourcePackage]
-> Progress String String SolverInstallPlan
planPackages verbosity comp platform solver
configFlags configExFlags installFlags
installedPkgIndex sourcePkgDb pkgConfigDb pkgSpecifiers =
resolveDependencies
platform (compilerInfo comp) pkgConfigDb
solver
resolverParams
>>= if onlyDeps then pruneInstallPlan pkgSpecifiers else return
where
resolverParams =
setMaxBackjumps (if maxBackjumps < 0 then Nothing
else Just maxBackjumps)
. setIndependentGoals independentGoals
. setReorderGoals reorderGoals
. setCountConflicts countConflicts
. setFineGrainedConflicts fineGrainedConflicts
. setMinimizeConflictSet minimizeConflictSet
. setAvoidReinstalls avoidReinstalls
. setShadowPkgs shadowPkgs
. setStrongFlags strongFlags
. setAllowBootLibInstalls allowBootLibInstalls
. setOnlyConstrained onlyConstrained
. setSolverVerbosity verbosity
. setPreferenceDefault (if upgradeDeps then PreferAllLatest
else PreferLatestForSelected)
. removeLowerBounds allowOlder
. removeUpperBounds allowNewer
. addPreferences
-- preferences from the config file or command line
[ PackageVersionPreference name ver
| PackageVersionConstraint name ver <- configPreferences configExFlags ]
. addConstraints
-- version constraints from the config file or command line
[ LabeledPackageConstraint (userToPackageConstraint pc) src
| (pc, src) <- configExConstraints configExFlags ]
. addConstraints
--FIXME: this just applies all flags to all targets which
-- is silly. We should check if the flags are appropriate
[ let pc = PackageConstraint
(scopeToplevel $ pkgSpecifierTarget pkgSpecifier)
(PackagePropertyFlags flags)
in LabeledPackageConstraint pc ConstraintSourceConfigFlagOrTarget
| let flags = configConfigurationsFlags configFlags
, not (nullFlagAssignment flags)
, pkgSpecifier <- pkgSpecifiers ]
. addConstraints
[ let pc = PackageConstraint
(scopeToplevel $ pkgSpecifierTarget pkgSpecifier)
(PackagePropertyStanzas stanzas)
in LabeledPackageConstraint pc ConstraintSourceConfigFlagOrTarget
| pkgSpecifier <- pkgSpecifiers ]
. (if reinstall then reinstallTargets else id)
-- Don't solve for executables, the legacy install codepath
-- doesn't understand how to install them
. setSolveExecutables (SolveExecutables False)
$ standardInstallPolicy
installedPkgIndex sourcePkgDb pkgSpecifiers
stanzas = [ TestStanzas | testsEnabled ]
++ [ BenchStanzas | benchmarksEnabled ]
testsEnabled = fromFlagOrDefault False $ configTests configFlags
benchmarksEnabled = fromFlagOrDefault False $ configBenchmarks configFlags
reinstall = fromFlag (installOverrideReinstall installFlags) ||
fromFlag (installReinstall installFlags)
reorderGoals = fromFlag (installReorderGoals installFlags)
countConflicts = fromFlag (installCountConflicts installFlags)
fineGrainedConflicts = fromFlag (installFineGrainedConflicts installFlags)
minimizeConflictSet = fromFlag (installMinimizeConflictSet installFlags)
independentGoals = fromFlag (installIndependentGoals installFlags)
avoidReinstalls = fromFlag (installAvoidReinstalls installFlags)
shadowPkgs = fromFlag (installShadowPkgs installFlags)
strongFlags = fromFlag (installStrongFlags installFlags)
maxBackjumps = fromFlag (installMaxBackjumps installFlags)
allowBootLibInstalls = fromFlag (installAllowBootLibInstalls installFlags)
onlyConstrained = fromFlag (installOnlyConstrained installFlags)
upgradeDeps = fromFlag (installUpgradeDeps installFlags)
onlyDeps = fromFlag (installOnlyDeps installFlags)
allowOlder = fromMaybe (AllowOlder mempty)
(configAllowOlder configExFlags)
allowNewer = fromMaybe (AllowNewer mempty)
(configAllowNewer configExFlags)
-- | Remove the provided targets from the install plan.
pruneInstallPlan :: Package targetpkg
=> [PackageSpecifier targetpkg]
-> SolverInstallPlan
-> Progress String String SolverInstallPlan
pruneInstallPlan pkgSpecifiers =
-- TODO: this is a general feature and should be moved to D.C.Dependency
-- Also, the InstallPlan.remove should return info more precise to the
-- problem, rather than the very general PlanProblem type.
either (Fail . explain) Done
. SolverInstallPlan.remove (\pkg -> packageName pkg `elem` targetnames)
where
explain :: [SolverInstallPlan.SolverPlanProblem] -> String
explain problems =
"Cannot select only the dependencies (as requested by the "
++ "'--only-dependencies' flag), "
++ (case pkgids of
[pkgid] -> "the package " ++ prettyShow pkgid ++ " is "
_ -> "the packages "
++ intercalate ", " (map prettyShow pkgids) ++ " are ")
++ "required by a dependency of one of the other targets."
where
pkgids =
nub [ depid
| SolverInstallPlan.PackageMissingDeps _ depids <- problems
, depid <- depids
, packageName depid `elem` targetnames ]
targetnames = map pkgSpecifierTarget pkgSpecifiers
-- ------------------------------------------------------------
-- * Informational messages
-- ------------------------------------------------------------
-- | Perform post-solver checks of the install plan and print it if
-- either requested or needed.
checkPrintPlan :: Verbosity
-> InstalledPackageIndex
-> InstallPlan
-> SourcePackageDb
-> InstallFlags
-> [PackageSpecifier UnresolvedSourcePackage]
-> IO ()
checkPrintPlan verbosity installed installPlan sourcePkgDb
installFlags pkgSpecifiers = do
-- User targets that are already installed.
let preExistingTargets =
[ p | let tgts = map pkgSpecifierTarget pkgSpecifiers,
InstallPlan.PreExisting p <- InstallPlan.toList installPlan,
packageName p `elem` tgts ]
-- If there's nothing to install, we print the already existing
-- target packages as an explanation.
when nothingToInstall $
notice verbosity $ unlines $
"All the requested packages are already installed:"
: map (prettyShow . packageId) preExistingTargets
++ ["Use --reinstall if you want to reinstall anyway."]
let lPlan =
[ (pkg, status)
| pkg <- InstallPlan.executionOrder installPlan
, let status = packageStatus installed pkg ]
-- Are any packages classified as reinstalls?
let reinstalledPkgs =
[ ipkg
| (_pkg, status) <- lPlan
, ipkg <- extractReinstalls status ]
-- Packages that are already broken.
let oldBrokenPkgs =
map Installed.installedUnitId
. PackageIndex.reverseDependencyClosure installed
. map (Installed.installedUnitId . fst)
. PackageIndex.brokenPackages
$ installed
let excluded = reinstalledPkgs ++ oldBrokenPkgs
-- Packages that are reverse dependencies of replaced packages are very
-- likely to be broken. We exclude packages that are already broken.
let newBrokenPkgs =
filter (\ p -> not (Installed.installedUnitId p `elem` excluded))
(PackageIndex.reverseDependencyClosure installed reinstalledPkgs)
let containsReinstalls = not (null reinstalledPkgs)
let breaksPkgs = not (null newBrokenPkgs)
let adaptedVerbosity
| containsReinstalls
, not overrideReinstall = modifyVerbosity (max verbose) verbosity
| otherwise = verbosity
-- We print the install plan if we are in a dry-run or if we are confronted
-- with a dangerous install plan.
when (dryRun || containsReinstalls && not overrideReinstall) $
printPlan (dryRun || breaksPkgs && not overrideReinstall)
adaptedVerbosity lPlan sourcePkgDb
-- If the install plan is dangerous, we print various warning messages. In
-- particular, if we can see that packages are likely to be broken, we even
-- bail out (unless installation has been forced with --force-reinstalls).
when containsReinstalls $ do
if breaksPkgs
then do
(if dryRun || overrideReinstall then warn else die') verbosity $ unlines $
"The following packages are likely to be broken by the reinstalls:"
: map (prettyShow . mungedId) newBrokenPkgs
++ if overrideReinstall
then if dryRun then [] else
["Continuing even though " ++
"the plan contains dangerous reinstalls."]
else
["Use --force-reinstalls if you want to install anyway."]
else unless dryRun $ warn verbosity
"Note that reinstalls are always dangerous. Continuing anyway..."
-- If we are explicitly told to not download anything, check that all packages
-- are already fetched.
let offline = fromFlagOrDefault False (installOfflineMode installFlags)
when offline $ do
let pkgs = [ confPkgSource cpkg
| InstallPlan.Configured cpkg <- InstallPlan.toList installPlan ]
notFetched <- fmap (map packageInfoId)
. filterM (fmap isNothing . checkFetched . packageSource)
$ pkgs
unless (null notFetched) $
die' verbosity $ "Can't download packages in offline mode. "
++ "Must download the following packages to proceed:\n"
++ intercalate ", " (map prettyShow notFetched)
++ "\nTry using 'cabal fetch'."
where
nothingToInstall = null (fst (InstallPlan.ready installPlan))
dryRun = fromFlag (installDryRun installFlags)
overrideReinstall = fromFlag (installOverrideReinstall installFlags)
data PackageStatus = NewPackage
| NewVersion [Version]
| Reinstall [UnitId] [PackageChange]
type PackageChange = MergeResult MungedPackageId MungedPackageId
extractReinstalls :: PackageStatus -> [UnitId]
extractReinstalls (Reinstall ipids _) = ipids
extractReinstalls _ = []
packageStatus :: InstalledPackageIndex
-> ReadyPackage
-> PackageStatus
packageStatus installedPkgIndex cpkg =
case PackageIndex.lookupPackageName installedPkgIndex
(packageName cpkg) of
[] -> NewPackage
ps -> case filter ((== mungedId cpkg)
. mungedId) (concatMap snd ps) of
[] -> NewVersion (map fst ps)
pkgs@(pkg:_) -> Reinstall (map Installed.installedUnitId pkgs)
(changes pkg cpkg)
where
changes :: Installed.InstalledPackageInfo
-> ReadyPackage
-> [PackageChange]
changes pkg (ReadyPackage pkg') = filter changed $
mergeBy (comparing mungedName)
-- deps of installed pkg
(resolveInstalledIds $ Installed.depends pkg)
-- deps of configured pkg
(resolveInstalledIds $ CD.nonSetupDeps (depends pkg'))
-- convert to source pkg ids via index
resolveInstalledIds :: [UnitId] -> [MungedPackageId]
resolveInstalledIds =
nub
. sort
. map mungedId
. mapMaybe (PackageIndex.lookupUnitId installedPkgIndex)
changed (InBoth pkgid pkgid') = pkgid /= pkgid'
changed _ = True
printPlan :: Bool -- is dry run
-> Verbosity
-> [(ReadyPackage, PackageStatus)]
-> SourcePackageDb
-> IO ()
printPlan dryRun verbosity plan sourcePkgDb = case plan of
[] -> return ()
pkgs
| verbosity >= Verbosity.verbose -> notice verbosity $ unlines $
("In order, the following " ++ wouldWill ++ " be installed:")
: map showPkgAndReason pkgs
| otherwise -> notice verbosity $ unlines $
("In order, the following " ++ wouldWill
++ " be installed (use -v for more details):")
: map showPkg pkgs
where
wouldWill | dryRun = "would"
| otherwise = "will"
showPkg (pkg, _) = prettyShow (packageId pkg) ++
showLatest (pkg)
showPkgAndReason (ReadyPackage pkg', pr) = prettyShow (packageId pkg') ++
showLatest pkg' ++
showFlagAssignment (nonDefaultFlags pkg') ++
showStanzas (confPkgStanzas pkg') ++
showDep pkg' ++
case pr of
NewPackage -> " (new package)"
NewVersion _ -> " (new version)"
Reinstall _ cs -> " (reinstall)" ++ case cs of
[] -> ""
diff -> " (changes: " ++ intercalate ", " (map change diff)
++ ")"
showLatest :: Package srcpkg => srcpkg -> String
showLatest pkg = case mLatestVersion of
Just latestVersion ->
if packageVersion pkg < latestVersion
then (" (latest: " ++ prettyShow latestVersion ++ ")")
else ""
Nothing -> ""
where
mLatestVersion :: Maybe Version
mLatestVersion = fmap packageVersion $
safeLast $
SourcePackageIndex.lookupPackageName
(packageIndex sourcePkgDb)
(packageName pkg)
toFlagAssignment :: [PackageFlag] -> FlagAssignment
toFlagAssignment = mkFlagAssignment . map (\ f -> (flagName f, flagDefault f))
nonDefaultFlags :: ConfiguredPackage loc -> FlagAssignment
nonDefaultFlags cpkg =
let defaultAssignment =
toFlagAssignment
(genPackageFlags (SourcePackage.packageDescription $
confPkgSource cpkg))
in confPkgFlags cpkg `diffFlagAssignment` defaultAssignment
showStanzas :: [OptionalStanza] -> String
showStanzas = concatMap ((" *" ++) . showStanza)
showFlagAssignment :: FlagAssignment -> String
showFlagAssignment = concatMap ((' ' :) . showFlagValue) . unFlagAssignment
change (OnlyInLeft pkgid) = prettyShow pkgid ++ " removed"
change (InBoth pkgid pkgid') = prettyShow pkgid ++ " -> "
++ prettyShow (mungedVersion pkgid')
change (OnlyInRight pkgid') = prettyShow pkgid' ++ " added"
showDep pkg | Just rdeps <- Map.lookup (packageId pkg) revDeps
= " (via: " ++ unwords (map prettyShow rdeps) ++ ")"
| otherwise = ""
revDepGraphEdges :: [(PackageId, PackageId)]
revDepGraphEdges = [ (rpid, packageId cpkg)
| (ReadyPackage cpkg, _) <- plan
, ConfiguredId
rpid
(Just
(PackageDescription.CLibName
PackageDescription.LMainLibName))
_
<- CD.flatDeps (confPkgDeps cpkg) ]
revDeps :: Map.Map PackageId [PackageId]
revDeps = Map.fromListWith (++) (map (fmap (:[])) revDepGraphEdges)
-- ------------------------------------------------------------
-- * Post installation stuff
-- ------------------------------------------------------------
-- | Report a solver failure. This works slightly differently to
-- 'postInstallActions', as (by definition) we don't have an install plan.
reportPlanningFailure :: Verbosity -> InstallArgs -> InstallContext -> String
-> IO ()
reportPlanningFailure verbosity
(_, _, comp, platform, _
,_, configFlags, _, installFlags, _, _, _)
(_, sourcePkgDb, _, _, pkgSpecifiers, _)
message = do
when reportFailure $ do
-- Only create reports for explicitly named packages
let pkgids = filter
(SourcePackageIndex.elemByPackageId (packageIndex sourcePkgDb)) $
mapMaybe theSpecifiedPackage pkgSpecifiers
buildReports = BuildReports.fromPlanningFailure platform
(compilerId comp) pkgids
(configConfigurationsFlags configFlags)
unless (null buildReports) $
info verbosity $
"Solver failure will be reported for "
++ intercalate "," (map prettyShow pkgids)
-- Save reports
BuildReports.storeLocal (compilerInfo comp)
(fromNubList $ installSummaryFile installFlags)
buildReports platform
-- Save solver log
case logFile of
Nothing -> return ()
Just template -> for_ pkgids $ \pkgid ->
let env = initialPathTemplateEnv pkgid dummyIpid
(compilerInfo comp) platform
path = fromPathTemplate $ substPathTemplate env template
in writeFile path message
where
reportFailure = fromFlag (installReportPlanningFailure installFlags)
logFile = flagToMaybe (installLogFile installFlags)
-- A IPID is calculated from the transitive closure of
-- dependencies, but when the solver fails we don't have that.
-- So we fail.
dummyIpid = error "reportPlanningFailure: installed package ID not available"
-- | If a 'PackageSpecifier' refers to a single package, return Just that
-- package.
theSpecifiedPackage :: Package pkg => PackageSpecifier pkg -> Maybe PackageId
theSpecifiedPackage pkgSpec =
case pkgSpec of
NamedPackage name [PackagePropertyVersion version]
-> PackageIdentifier name <$> trivialRange version
NamedPackage _ _ -> Nothing
SpecificSourcePackage pkg -> Just $ packageId pkg
where
-- | If a range includes only a single version, return Just that version.
trivialRange :: VersionRange -> Maybe Version
trivialRange = foldVersionRange
Nothing
Just -- "== v"
(\_ -> Nothing)
(\_ -> Nothing)
(\_ _ -> Nothing)
(\_ _ -> Nothing)
-- | Various stuff we do after successful or unsuccessfully installing a bunch
-- of packages. This includes:
--
-- * build reporting, local and remote
-- * symlinking binaries
-- * updating indexes
-- * updating world file
-- * error reporting
--
postInstallActions :: Verbosity
-> InstallArgs
-> [UserTarget]
-> InstallPlan
-> BuildOutcomes
-> IO ()
postInstallActions verbosity
(packageDBs, _, comp, platform, progdb
,globalFlags, configFlags, _, installFlags, _, _, _)
targets installPlan buildOutcomes = do
unless oneShot $
World.insert verbosity worldFile
--FIXME: does not handle flags
[ World.WorldPkgInfo (Dependency pn vr mainLibSet) mempty
| UserTargetNamed (PackageVersionConstraint pn vr) <- targets ]
let buildReports = BuildReports.fromInstallPlan platform (compilerId comp)
installPlan buildOutcomes
BuildReports.storeLocal (compilerInfo comp)
(fromNubList $ installSummaryFile installFlags)
buildReports
platform
when (reportingLevel >= AnonymousReports) $
BuildReports.storeAnonymous buildReports
when (reportingLevel == DetailedReports) $
storeDetailedBuildReports verbosity logsDir buildReports
regenerateHaddockIndex verbosity packageDBs comp platform progdb
configFlags installFlags buildOutcomes
symlinkBinaries verbosity platform comp configFlags installFlags
installPlan buildOutcomes
printBuildFailures verbosity buildOutcomes
where
reportingLevel = fromFlag (installBuildReports installFlags)
logsDir = fromFlag (globalLogsDir globalFlags)
oneShot = fromFlag (installOneShot installFlags)
worldFile = fromFlag $ globalWorldFile globalFlags
storeDetailedBuildReports :: Verbosity -> FilePath
-> [(BuildReports.BuildReport, Maybe Repo)] -> IO ()
storeDetailedBuildReports verbosity logsDir reports = sequence_
[ do dotCabal <- getCabalDir
let logFileName = prettyShow (BuildReports.package report) <.> "log"
logFile = logsDir </> logFileName
reportsDir = dotCabal </> "reports" </> unRepoName (remoteRepoName remoteRepo)
reportFile = reportsDir </> logFileName
handleMissingLogFile $ do
buildLog <- readFile logFile
createDirectoryIfMissing True reportsDir -- FIXME
writeFile reportFile (show (showBuildReport report, buildLog))
| (report, Just repo) <- reports
, Just remoteRepo <- [maybeRepoRemote repo]
, isLikelyToHaveLogFile (BuildReports.installOutcome report) ]
where
isLikelyToHaveLogFile BuildReports.ConfigureFailed {} = True
isLikelyToHaveLogFile BuildReports.BuildFailed {} = True
isLikelyToHaveLogFile BuildReports.InstallFailed {} = True
isLikelyToHaveLogFile BuildReports.InstallOk {} = True
isLikelyToHaveLogFile _ = False
handleMissingLogFile = Exception.handleJust missingFile $ \ioe ->
warn verbosity $ "Missing log file for build report: "
++ fromMaybe "" (ioeGetFileName ioe)
missingFile ioe
| isDoesNotExistError ioe = Just ioe
missingFile _ = Nothing
regenerateHaddockIndex :: Verbosity
-> [PackageDB]
-> Compiler
-> Platform
-> ProgramDb
-> ConfigFlags
-> InstallFlags
-> BuildOutcomes
-> IO ()
regenerateHaddockIndex verbosity packageDBs comp platform progdb
configFlags installFlags buildOutcomes
| haddockIndexFileIsRequested && shouldRegenerateHaddockIndex = do
defaultDirs <- InstallDirs.defaultInstallDirs
(compilerFlavor comp)
(fromFlag (configUserInstall configFlags))
True
let indexFileTemplate = fromFlag (installHaddockIndex installFlags)
indexFile = substHaddockIndexFileName defaultDirs indexFileTemplate
notice verbosity $
"Updating documentation index " ++ indexFile
--TODO: might be nice if the install plan gave us the new InstalledPackageInfo
installedPkgIndex <- getInstalledPackages verbosity comp packageDBs progdb
Haddock.regenerateHaddockIndex verbosity installedPkgIndex progdb indexFile
| otherwise = return ()
where
haddockIndexFileIsRequested =
fromFlag (installDocumentation installFlags)
&& isJust (flagToMaybe (installHaddockIndex installFlags))
-- We want to regenerate the index if some new documentation was actually
-- installed. Since the index can be only per-user or per-sandbox (see
-- #1337), we don't do it for global installs or special cases where we're
-- installing into a specific db.
shouldRegenerateHaddockIndex = normalUserInstall && someDocsWereInstalled buildOutcomes
where
someDocsWereInstalled = any installedDocs . Map.elems
installedDocs (Right (BuildResult DocsOk _ _)) = True
installedDocs _ = False
normalUserInstall = (UserPackageDB `elem` packageDBs)
&& all (not . isSpecificPackageDB) packageDBs
isSpecificPackageDB (SpecificPackageDB _) = True
isSpecificPackageDB _ = False
substHaddockIndexFileName defaultDirs = fromPathTemplate
. substPathTemplate env
where
env = env0 ++ installDirsTemplateEnv absoluteDirs
env0 = InstallDirs.compilerTemplateEnv (compilerInfo comp)
++ InstallDirs.platformTemplateEnv platform
++ InstallDirs.abiTemplateEnv (compilerInfo comp) platform
absoluteDirs = InstallDirs.substituteInstallDirTemplates
env0 templateDirs
templateDirs = InstallDirs.combineInstallDirs fromFlagOrDefault
defaultDirs (configInstallDirs configFlags)
symlinkBinaries :: Verbosity
-> Platform -> Compiler
-> ConfigFlags
-> InstallFlags
-> InstallPlan
-> BuildOutcomes
-> IO ()
symlinkBinaries verbosity platform comp configFlags installFlags
plan buildOutcomes = do
failed <- InstallSymlink.symlinkBinaries platform comp
NeverOverwrite
configFlags installFlags
plan buildOutcomes
case failed of
[] -> return ()
[(_, exe, path)] ->
warn verbosity $
"could not create a symlink in " ++ bindir ++ " for "
++ prettyShow exe ++ " because the file exists there already but is not "
++ "managed by cabal. You can create a symlink for this executable "
++ "manually if you wish. The executable file has been installed at "
++ path
exes ->
warn verbosity $
"could not create symlinks in " ++ bindir ++ " for "
++ intercalate ", " [ prettyShow exe | (_, exe, _) <- exes ]
++ " because the files exist there already and are not "
++ "managed by cabal. You can create symlinks for these executables "
++ "manually if you wish. The executable files have been installed at "
++ intercalate ", " [ path | (_, _, path) <- exes ]
where
bindir = fromFlag (installSymlinkBinDir installFlags)
printBuildFailures :: Verbosity -> BuildOutcomes -> IO ()
printBuildFailures verbosity buildOutcomes =
case [ (pkgid, failure)
| (pkgid, Left failure) <- Map.toList buildOutcomes ] of
[] -> return ()
failed -> die' verbosity . unlines
$ "Error: some packages failed to install:"
: [ prettyShow pkgid ++ printFailureReason reason
| (pkgid, reason) <- failed ]
where
printFailureReason reason = case reason of
DependentFailed pkgid -> " depends on " ++ prettyShow pkgid
++ " which failed to install."
DownloadFailed e -> " failed while downloading the package."
++ showException e
UnpackFailed e -> " failed while unpacking the package."
++ showException e
ConfigureFailed e -> " failed during the configure step."
++ showException e
BuildFailed e -> " failed during the building phase."
++ showException e
TestsFailed e -> " failed during the tests phase."
++ showException e