-
Notifications
You must be signed in to change notification settings - Fork 698
/
ProjectBuilding.hs
1889 lines (1730 loc) · 64.3 KB
/
ProjectBuilding.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 BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE NoMonoLocalBinds #-}
module Distribution.Client.ProjectBuilding
( -- * Dry run phase
-- | What bits of the plan will we execute? The dry run does not change
-- anything but tells us what will need to be built.
rebuildTargetsDryRun
, improveInstallPlanWithUpToDatePackages
-- ** Build status
-- | This is the detailed status information we get from the dry run.
, BuildStatusMap
, BuildStatus (..)
, BuildStatusRebuild (..)
, BuildReason (..)
, MonitorChangedReason (..)
, buildStatusToString
-- * Build phase
-- | Now we actually execute the plan.
, rebuildTargets
-- ** Build outcomes
-- | This is the outcome for each package of executing the plan.
-- For each package, did the build succeed or fail?
, BuildOutcomes
, BuildOutcome
, BuildResult (..)
, BuildFailure (..)
, BuildFailureReason (..)
) where
import Distribution.Client.Compat.Prelude
import Prelude ()
import Distribution.Client.PackageHash (renderPackageHashInputs)
import Distribution.Client.ProjectBuilding.Types
import Distribution.Client.ProjectConfig
import Distribution.Client.ProjectConfig.Types
import Distribution.Client.ProjectPlanning
import Distribution.Client.ProjectPlanning.Types
import Distribution.Client.RebuildMonad
import Distribution.Client.Store
import Distribution.Client.DistDirLayout
import Distribution.Client.FetchUtils
import Distribution.Client.FileMonitor
import Distribution.Client.GlobalFlags (RepoContext)
import Distribution.Client.InstallPlan
( GenericInstallPlan
, GenericPlanPackage
, IsUnit
)
import qualified Distribution.Client.InstallPlan as InstallPlan
import Distribution.Client.JobControl
import Distribution.Client.Setup
( filterConfigureFlags
, filterHaddockArgs
, filterHaddockFlags
, filterTestFlags
)
import Distribution.Client.SetupWrapper
import Distribution.Client.SourceFiles
import Distribution.Client.SrcDist (allPackageSourceFiles)
import qualified Distribution.Client.Tar as Tar
import Distribution.Client.Types hiding
( BuildFailure (..)
, BuildOutcome
, BuildOutcomes
, BuildResult (..)
)
import Distribution.Client.Utils
( ProgressPhase (..)
, findOpenProgramLocation
, numberOfProcessors
, progressMessage
, removeExistingFile
)
import Distribution.Compat.Lens
import Distribution.InstalledPackageInfo (InstalledPackageInfo)
import qualified Distribution.InstalledPackageInfo as Installed
import Distribution.Package
import qualified Distribution.PackageDescription as PD
import Distribution.Simple.BuildPaths (haddockDirName)
import Distribution.Simple.Command (CommandUI)
import Distribution.Simple.Compiler
( Compiler
, PackageDB (..)
, compilerId
, jsemSupported
)
import qualified Distribution.Simple.InstallDirs as InstallDirs
import Distribution.Simple.LocalBuildInfo
( ComponentName (..)
, LibraryName (..)
)
import Distribution.Simple.Program
import qualified Distribution.Simple.Register as Cabal
import qualified Distribution.Simple.Setup as Cabal
import Distribution.Types.BuildType
import Distribution.Types.PackageDescription.Lens (componentModules)
import Distribution.Compat.Graph (IsNode (..))
import Distribution.Simple.Utils
import Distribution.Version
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.Lazy.Char8 as LBS.Char8
import qualified Data.List.NonEmpty as NE
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Text.PrettyPrint as Disp
import Control.Exception (Handler (..), SomeAsyncException, assert, bracket, catches, handle)
import System.Directory (canonicalizePath, createDirectoryIfMissing, doesDirectoryExist, doesFileExist, removeFile, renameDirectory)
import System.FilePath (dropDrive, makeRelative, normalise, takeDirectory, (<.>), (</>))
import System.IO (Handle, IOMode (AppendMode), withFile)
import System.Semaphore (SemaphoreName (..))
import Distribution.Client.Errors
import Distribution.Compat.Directory (listDirectory)
import Distribution.Simple.Flag (fromFlagOrDefault)
------------------------------------------------------------------------------
-- * Overall building strategy.
------------------------------------------------------------------------------
--
-- We start with an 'ElaboratedInstallPlan' that has already been improved by
-- reusing packages from the store, and pruned to include only the targets of
-- interest and their dependencies. So the remaining packages in the
-- 'InstallPlan.Configured' state are ones we either need to build or rebuild.
--
-- First, we do a preliminary dry run phase where we work out which packages
-- we really need to (re)build, and for the ones we do need to build which
-- build phase to start at.
--
-- We use this to improve the 'ElaboratedInstallPlan' again by changing
-- up-to-date 'InstallPlan.Configured' packages to 'InstallPlan.Installed'
-- so that the build phase will skip them.
--
-- Then we execute the plan, that is actually build packages. The outcomes of
-- trying to build all the packages are collected and returned.
--
-- We split things like this (dry run and execute) for a couple reasons.
-- Firstly we need to be able to do dry runs anyway, and these need to be
-- reasonably accurate in terms of letting users know what (and why) things
-- are going to be (re)built.
--
-- Given that we need to be able to do dry runs, it would not be great if
-- we had to repeat all the same work when we do it for real. Not only is
-- it duplicate work, but it's duplicate code which is likely to get out of
-- sync. So we do things only once. We preserve info we discover in the dry
-- run phase and rely on it later when we build things for real. This also
-- somewhat simplifies the build phase. So this way the dry run can't so
-- easily drift out of sync with the real thing since we're relying on the
-- info it produces.
--
-- An additional advantage is that it makes it easier to debug rebuild
-- errors (ie rebuilding too much or too little), since all the rebuild
-- decisions are made without making any state changes at the same time
-- (that would make it harder to reproduce the problem situation).
--
-- Finally, we can use the dry run build status and the build outcomes to
-- give us some information on the overall status of packages in the project.
-- This includes limited information about the status of things that were
-- not actually in the subset of the plan that was used for the dry run or
-- execution phases. In particular we may know that some packages are now
-- definitely out of date. See "Distribution.Client.ProjectPlanOutput" for
-- details.
------------------------------------------------------------------------------
-- * Dry run: what bits of the 'ElaboratedInstallPlan' will we execute?
------------------------------------------------------------------------------
-- Refer to ProjectBuilding.Types for details of these important types:
-- type BuildStatusMap = ...
-- data BuildStatus = ...
-- data BuildStatusRebuild = ...
-- data BuildReason = ...
-- | Do the dry run pass. This is a prerequisite of 'rebuildTargets'.
--
-- It gives us the 'BuildStatusMap'. This should be used with
-- 'improveInstallPlanWithUpToDatePackages' to give an improved version of
-- the 'ElaboratedInstallPlan' with packages switched to the
-- 'InstallPlan.Installed' state when we find that they're already up to date.
rebuildTargetsDryRun
:: DistDirLayout
-> ElaboratedSharedConfig
-> ElaboratedInstallPlan
-> IO BuildStatusMap
rebuildTargetsDryRun distDirLayout@DistDirLayout{..} shared =
-- Do the various checks to work out the 'BuildStatus' of each package
foldMInstallPlanDepOrder dryRunPkg
where
dryRunPkg
:: ElaboratedPlanPackage
-> [BuildStatus]
-> IO BuildStatus
dryRunPkg (InstallPlan.PreExisting _pkg) _depsBuildStatus =
return BuildStatusPreExisting
dryRunPkg (InstallPlan.Installed _pkg) _depsBuildStatus =
return BuildStatusInstalled
dryRunPkg (InstallPlan.Configured pkg) depsBuildStatus = do
mloc <- checkFetched (elabPkgSourceLocation pkg)
case mloc of
Nothing -> return BuildStatusDownload
Just (LocalUnpackedPackage srcdir) ->
-- For the case of a user-managed local dir, irrespective of the
-- build style, we build from that directory and put build
-- artifacts under the shared dist directory.
dryRunLocalPkg pkg depsBuildStatus srcdir
-- The rest cases are all tarball cases are,
-- and handled the same as each other though depending on the build style.
Just (LocalTarballPackage tarball) ->
dryRunTarballPkg pkg depsBuildStatus tarball
Just (RemoteTarballPackage _ tarball) ->
dryRunTarballPkg pkg depsBuildStatus tarball
Just (RepoTarballPackage _ _ tarball) ->
dryRunTarballPkg pkg depsBuildStatus tarball
Just (RemoteSourceRepoPackage _repo tarball) ->
dryRunTarballPkg pkg depsBuildStatus tarball
dryRunTarballPkg
:: ElaboratedConfiguredPackage
-> [BuildStatus]
-> FilePath
-> IO BuildStatus
dryRunTarballPkg pkg depsBuildStatus tarball =
case elabBuildStyle pkg of
BuildAndInstall -> return (BuildStatusUnpack tarball)
BuildInplaceOnly{} -> do
-- TODO: [nice to have] use a proper file monitor rather
-- than this dir exists test
exists <- doesDirectoryExist srcdir
if exists
then dryRunLocalPkg pkg depsBuildStatus srcdir
else return (BuildStatusUnpack tarball)
where
srcdir :: FilePath
srcdir = distUnpackedSrcDirectory (packageId pkg)
dryRunLocalPkg
:: ElaboratedConfiguredPackage
-> [BuildStatus]
-> FilePath
-> IO BuildStatus
dryRunLocalPkg pkg depsBuildStatus srcdir = do
-- Go and do lots of I/O, reading caches and probing files to work out
-- if anything has changed
change <-
checkPackageFileMonitorChanged
packageFileMonitor
pkg
srcdir
depsBuildStatus
case change of
-- It did change, giving us 'BuildStatusRebuild' info on why
Left rebuild ->
return (BuildStatusRebuild srcdir rebuild)
-- No changes, the package is up to date. Use the saved build results.
Right buildResult ->
return (BuildStatusUpToDate buildResult)
where
packageFileMonitor :: PackageFileMonitor
packageFileMonitor =
newPackageFileMonitor
shared
distDirLayout
(elabDistDirParams shared pkg)
-- | A specialised traversal over the packages in an install plan.
--
-- The packages are visited in dependency order, starting with packages with no
-- dependencies. The result for each package is accumulated into a 'Map' and
-- returned as the final result. In addition, when visiting a package, the
-- visiting function is passed the results for all the immediate package
-- dependencies. This can be used to propagate information from dependencies.
foldMInstallPlanDepOrder
:: forall m ipkg srcpkg b
. (Monad m, IsUnit ipkg, IsUnit srcpkg)
=> ( GenericPlanPackage ipkg srcpkg
-> [b]
-> m b
)
-> GenericInstallPlan ipkg srcpkg
-> m (Map UnitId b)
foldMInstallPlanDepOrder visit =
go Map.empty . InstallPlan.reverseTopologicalOrder
where
go
:: Map UnitId b
-> [GenericPlanPackage ipkg srcpkg]
-> m (Map UnitId b)
go !results [] = return results
go !results (pkg : pkgs) = do
-- we go in the right order so the results map has entries for all deps
let depresults :: [b]
depresults =
map
( \ipkgid ->
let result = Map.findWithDefault (error "foldMInstallPlanDepOrder") ipkgid results
in result
)
(InstallPlan.depends pkg)
result <- visit pkg depresults
let results' = Map.insert (nodeKey pkg) result results
go results' pkgs
improveInstallPlanWithUpToDatePackages
:: BuildStatusMap
-> ElaboratedInstallPlan
-> ElaboratedInstallPlan
improveInstallPlanWithUpToDatePackages pkgsBuildStatus =
InstallPlan.installed canPackageBeImproved
where
canPackageBeImproved :: ElaboratedConfiguredPackage -> Bool
canPackageBeImproved pkg =
case Map.lookup (installedUnitId pkg) pkgsBuildStatus of
Just BuildStatusUpToDate{} -> True
Just _ -> False
Nothing ->
error $
"improveInstallPlanWithUpToDatePackages: "
++ prettyShow (packageId pkg)
++ " not in status map"
-----------------------------
-- Package change detection
--
-- | As part of the dry run for local unpacked packages we have to check if the
-- package config or files have changed. That is the purpose of
-- 'PackageFileMonitor' and 'checkPackageFileMonitorChanged'.
--
-- When a package is (re)built, the monitor must be updated to reflect the new
-- state of the package. Because we sometimes build without reconfiguring the
-- state updates are split into two, one for package config changes and one
-- for other changes. This is the purpose of 'updatePackageConfigFileMonitor'
-- and 'updatePackageBuildFileMonitor'.
data PackageFileMonitor = PackageFileMonitor
{ pkgFileMonitorConfig :: FileMonitor ElaboratedConfiguredPackage ()
, pkgFileMonitorBuild :: FileMonitor (Set ComponentName) BuildResultMisc
, pkgFileMonitorReg :: FileMonitor () (Maybe InstalledPackageInfo)
}
-- | This is all the components of the 'BuildResult' other than the
-- @['InstalledPackageInfo']@.
--
-- We have to split up the 'BuildResult' components since they get produced
-- at different times (or rather, when different things change).
type BuildResultMisc = (DocsResult, TestsResult)
newPackageFileMonitor
:: ElaboratedSharedConfig
-> DistDirLayout
-> DistDirParams
-> PackageFileMonitor
newPackageFileMonitor
shared
DistDirLayout{distPackageCacheFile}
dparams =
PackageFileMonitor
{ pkgFileMonitorConfig =
FileMonitor
{ fileMonitorCacheFile = distPackageCacheFile dparams "config"
, fileMonitorKeyValid = (==) `on` normaliseConfiguredPackage shared
, fileMonitorCheckIfOnlyValueChanged = False
}
, pkgFileMonitorBuild =
FileMonitor
{ fileMonitorCacheFile = distPackageCacheFile dparams "build"
, fileMonitorKeyValid = \componentsToBuild componentsAlreadyBuilt ->
componentsToBuild `Set.isSubsetOf` componentsAlreadyBuilt
, fileMonitorCheckIfOnlyValueChanged = True
}
, pkgFileMonitorReg =
newFileMonitor (distPackageCacheFile dparams "registration")
}
-- | Helper function for 'checkPackageFileMonitorChanged',
-- 'updatePackageConfigFileMonitor' and 'updatePackageBuildFileMonitor'.
--
-- It selects the info from a 'ElaboratedConfiguredPackage' that are used by
-- the 'FileMonitor's (in the 'PackageFileMonitor') to detect value changes.
packageFileMonitorKeyValues
:: ElaboratedConfiguredPackage
-> (ElaboratedConfiguredPackage, Set ComponentName)
packageFileMonitorKeyValues elab =
(elab_config, buildComponents)
where
-- The first part is the value used to guard (re)configuring the package.
-- That is, if this value changes then we will reconfigure.
-- The ElaboratedConfiguredPackage consists mostly (but not entirely) of
-- information that affects the (re)configure step. But those parts that
-- do not affect the configure step need to be nulled out. Those parts are
-- the specific targets that we're going to build.
--
-- Additionally we null out the parts that don't affect the configure step because they're simply
-- about how tests or benchmarks are run
-- TODO there may be more things to null here too, in the future.
elab_config :: ElaboratedConfiguredPackage
elab_config =
elab
{ elabBuildTargets = []
, elabTestTargets = []
, elabBenchTargets = []
, elabReplTarget = []
, elabHaddockTargets = []
, elabBuildHaddocks = False
, elabTestMachineLog = Nothing
, elabTestHumanLog = Nothing
, elabTestShowDetails = Nothing
, elabTestKeepTix = False
, elabTestTestOptions = []
, elabBenchmarkOptions = []
}
-- The second part is the value used to guard the build step. So this is
-- more or less the opposite of the first part, as it's just the info about
-- what targets we're going to build.
--
buildComponents :: Set ComponentName
buildComponents = elabBuildTargetWholeComponents elab
-- | Do all the checks on whether a package has changed and thus needs either
-- rebuilding or reconfiguring and rebuilding.
checkPackageFileMonitorChanged
:: PackageFileMonitor
-> ElaboratedConfiguredPackage
-> FilePath
-> [BuildStatus]
-> IO (Either BuildStatusRebuild BuildResult)
checkPackageFileMonitorChanged
PackageFileMonitor{..}
pkg
srcdir
depsBuildStatus = do
-- TODO: [nice to have] some debug-level message about file
-- changes, like rerunIfChanged
configChanged <-
checkFileMonitorChanged
pkgFileMonitorConfig
srcdir
pkgconfig
case configChanged of
MonitorChanged monitorReason ->
return (Left (BuildStatusConfigure monitorReason'))
where
monitorReason' = fmap (const ()) monitorReason
MonitorUnchanged () _
-- The configChanged here includes the identity of the dependencies,
-- so depsBuildStatus is just needed for the changes in the content
-- of dependencies.
| any buildStatusRequiresBuild depsBuildStatus -> do
regChanged <- checkFileMonitorChanged pkgFileMonitorReg srcdir ()
let mreg = changedToMaybe regChanged
return (Left (BuildStatusBuild mreg BuildReasonDepsRebuilt))
| otherwise -> do
buildChanged <-
checkFileMonitorChanged
pkgFileMonitorBuild
srcdir
buildComponents
regChanged <-
checkFileMonitorChanged
pkgFileMonitorReg
srcdir
()
let mreg = changedToMaybe regChanged
case (buildChanged, regChanged) of
(MonitorChanged (MonitoredValueChanged prevBuildComponents), _) ->
return (Left (BuildStatusBuild mreg buildReason))
where
buildReason = BuildReasonExtraTargets prevBuildComponents
(MonitorChanged monitorReason, _) ->
return (Left (BuildStatusBuild mreg buildReason))
where
buildReason = BuildReasonFilesChanged monitorReason'
monitorReason' = fmap (const ()) monitorReason
(MonitorUnchanged _ _, MonitorChanged monitorReason) ->
-- this should only happen if the file is corrupt or been
-- manually deleted. We don't want to bother with another
-- phase just for this, so we'll reregister by doing a build.
return (Left (BuildStatusBuild Nothing buildReason))
where
buildReason = BuildReasonFilesChanged monitorReason'
monitorReason' = fmap (const ()) monitorReason
(MonitorUnchanged _ _, MonitorUnchanged _ _)
| pkgHasEphemeralBuildTargets pkg ->
return (Left (BuildStatusBuild mreg buildReason))
where
buildReason = BuildReasonEphemeralTargets
(MonitorUnchanged buildResult _, MonitorUnchanged _ _) ->
return $
Right
BuildResult
{ buildResultDocs = docsResult
, buildResultTests = testsResult
, buildResultLogFile = Nothing
}
where
(docsResult, testsResult) = buildResult
where
(pkgconfig, buildComponents) = packageFileMonitorKeyValues pkg
changedToMaybe :: MonitorChanged a b -> Maybe b
changedToMaybe (MonitorChanged _) = Nothing
changedToMaybe (MonitorUnchanged x _) = Just x
updatePackageConfigFileMonitor
:: PackageFileMonitor
-> FilePath
-> ElaboratedConfiguredPackage
-> IO ()
updatePackageConfigFileMonitor
PackageFileMonitor{pkgFileMonitorConfig}
srcdir
pkg =
updateFileMonitor
pkgFileMonitorConfig
srcdir
Nothing
[]
pkgconfig
()
where
(pkgconfig, _buildComponents) = packageFileMonitorKeyValues pkg
updatePackageBuildFileMonitor
:: PackageFileMonitor
-> FilePath
-> MonitorTimestamp
-> ElaboratedConfiguredPackage
-> BuildStatusRebuild
-> [MonitorFilePath]
-> BuildResultMisc
-> IO ()
updatePackageBuildFileMonitor
PackageFileMonitor{pkgFileMonitorBuild}
srcdir
timestamp
pkg
pkgBuildStatus
monitors
buildResult =
updateFileMonitor
pkgFileMonitorBuild
srcdir
(Just timestamp)
monitors
buildComponents'
buildResult
where
(_pkgconfig, buildComponents) = packageFileMonitorKeyValues pkg
-- If the only thing that's changed is that we're now building extra
-- components, then we can avoid later unnecessary rebuilds by saving the
-- total set of components that have been built, namely the union of the
-- existing ones plus the new ones. If files also changed this would be
-- the wrong thing to do. Note that we rely on the
-- fileMonitorCheckIfOnlyValueChanged = True mode to get this guarantee
-- that it's /only/ the value that changed not any files that changed.
buildComponents' =
case pkgBuildStatus of
BuildStatusBuild _ (BuildReasonExtraTargets prevBuildComponents) ->
buildComponents `Set.union` prevBuildComponents
_ -> buildComponents
updatePackageRegFileMonitor
:: PackageFileMonitor
-> FilePath
-> Maybe InstalledPackageInfo
-> IO ()
updatePackageRegFileMonitor
PackageFileMonitor{pkgFileMonitorReg}
srcdir
mipkg =
updateFileMonitor
pkgFileMonitorReg
srcdir
Nothing
[]
()
mipkg
invalidatePackageRegFileMonitor :: PackageFileMonitor -> IO ()
invalidatePackageRegFileMonitor PackageFileMonitor{pkgFileMonitorReg} =
removeExistingFile (fileMonitorCacheFile pkgFileMonitorReg)
------------------------------------------------------------------------------
-- * Doing it: executing an 'ElaboratedInstallPlan'
------------------------------------------------------------------------------
-- Refer to ProjectBuilding.Types for details of these important types:
-- type BuildOutcomes = ...
-- type BuildOutcome = ...
-- data BuildResult = ...
-- data BuildFailure = ...
-- data BuildFailureReason = ...
-- | Build things for real.
--
-- It requires the 'BuildStatusMap' gathered by 'rebuildTargetsDryRun'.
rebuildTargets
:: Verbosity
-> ProjectConfig
-> DistDirLayout
-> StoreDirLayout
-> ElaboratedInstallPlan
-> ElaboratedSharedConfig
-> BuildStatusMap
-> BuildTimeSettings
-> IO BuildOutcomes
rebuildTargets
verbosity
ProjectConfig
{ projectConfigBuildOnly = config
}
distDirLayout@DistDirLayout{..}
storeDirLayout
installPlan
sharedPackageConfig@ElaboratedSharedConfig
{ pkgConfigCompiler = compiler
, pkgConfigCompilerProgs = progdb
}
pkgsBuildStatus
buildSettings@BuildTimeSettings
{ buildSettingNumJobs
, buildSettingKeepGoing
}
| fromFlagOrDefault False (projectConfigOfflineMode config) && not (null packagesToDownload) = return offlineError
| otherwise = do
-- Concurrency control: create the job controller and concurrency limits
-- for downloading, building and installing.
mkJobControl <- case buildSettingNumJobs of
Serial -> newSerialJobControl
NumJobs n -> newParallelJobControl (fromMaybe numberOfProcessors n)
UseSem n ->
if jsemSupported compiler
then newSemaphoreJobControl n
else do
warn verbosity "-jsem is not supported by the selected compiler, falling back to normal parallelism control."
newParallelJobControl n
registerLock <- newLock -- serialise registration
cacheLock <- newLock -- serialise access to setup exe cache
-- TODO: [code cleanup] eliminate setup exe cache
info verbosity $
"Executing install plan "
++ case buildSettingNumJobs of
NumJobs n -> " in parallel using " ++ show n ++ " threads."
UseSem n -> " in parallel using a semaphore with " ++ show n ++ " slots."
Serial -> " serially."
createDirectoryIfMissingVerbose verbosity True distBuildRootDirectory
createDirectoryIfMissingVerbose verbosity True distTempDirectory
traverse_ (createPackageDBIfMissing verbosity compiler progdb) packageDBsToUse
bracket (pure mkJobControl) cleanupJobControl $ \jobControl -> do
-- Before traversing the install plan, preemptively find all packages that
-- will need to be downloaded and start downloading them.
asyncDownloadPackages
verbosity
withRepoCtx
installPlan
pkgsBuildStatus
$ \downloadMap ->
-- For each package in the plan, in dependency order, but in parallel...
InstallPlan.execute
mkJobControl
keepGoing
(BuildFailure Nothing . DependentFailed . packageId)
installPlan
$ \pkg ->
-- TODO: review exception handling
handle (\(e :: BuildFailure) -> return (Left e)) $ fmap Right $ do
let uid = installedUnitId pkg
pkgBuildStatus = Map.findWithDefault (error "rebuildTargets") uid pkgsBuildStatus
rebuildTarget
verbosity
distDirLayout
storeDirLayout
(jobControlSemaphore jobControl)
buildSettings
downloadMap
registerLock
cacheLock
sharedPackageConfig
installPlan
pkg
pkgBuildStatus
where
keepGoing = buildSettingKeepGoing
withRepoCtx =
projectConfigWithBuilderRepoContext
verbosity
buildSettings
packageDBsToUse =
-- all the package dbs we may need to create
(Set.toList . Set.fromList)
[ pkgdb
| InstallPlan.Configured elab <- InstallPlan.toList installPlan
, pkgdb <-
concat
[ elabBuildPackageDBStack elab
, elabRegisterPackageDBStack elab
, elabSetupPackageDBStack elab
]
]
offlineError :: BuildOutcomes
offlineError = Map.fromList . map makeBuildOutcome $ packagesToDownload
where
makeBuildOutcome :: ElaboratedConfiguredPackage -> (UnitId, BuildOutcome)
makeBuildOutcome
ElaboratedConfiguredPackage
{ elabUnitId
, elabPkgSourceId = PackageIdentifier{pkgName, pkgVersion}
} =
( elabUnitId
, Left
( BuildFailure
{ buildFailureLogFile = Nothing
, buildFailureReason = GracefulFailure $ makeError pkgName pkgVersion
}
)
)
makeError :: PackageName -> Version -> String
makeError n v =
"--offline was specified, hence refusing to download the package: "
++ unPackageName n
++ " version "
++ Disp.render (pretty v)
packagesToDownload :: [ElaboratedConfiguredPackage]
packagesToDownload =
[ elab | InstallPlan.Configured elab <- InstallPlan.reverseTopologicalOrder installPlan, isRemote $ elabPkgSourceLocation elab
]
where
isRemote :: PackageLocation a -> Bool
isRemote (RemoteTarballPackage _ _) = True
isRemote (RepoTarballPackage{}) = True
isRemote (RemoteSourceRepoPackage _ _) = True
isRemote _ = False
-- | Create a package DB if it does not currently exist. Note that this action
-- is /not/ safe to run concurrently.
createPackageDBIfMissing
:: Verbosity
-> Compiler
-> ProgramDb
-> PackageDB
-> IO ()
createPackageDBIfMissing
verbosity
compiler
progdb
(SpecificPackageDB dbPath) = do
exists <- Cabal.doesPackageDBExist dbPath
unless exists $ do
createDirectoryIfMissingVerbose verbosity True (takeDirectory dbPath)
Cabal.createPackageDB verbosity compiler progdb False dbPath
createPackageDBIfMissing _ _ _ _ = return ()
-- | Given all the context and resources, (re)build an individual package.
rebuildTarget
:: Verbosity
-> DistDirLayout
-> StoreDirLayout
-> Maybe SemaphoreName
-> BuildTimeSettings
-> AsyncFetchMap
-> Lock
-> Lock
-> ElaboratedSharedConfig
-> ElaboratedInstallPlan
-> ElaboratedReadyPackage
-> BuildStatus
-> IO BuildResult
rebuildTarget
verbosity
distDirLayout@DistDirLayout{distBuildDirectory}
storeDirLayout
semaphoreName
buildSettings
downloadMap
registerLock
cacheLock
sharedPackageConfig
plan
rpkg@(ReadyPackage pkg)
pkgBuildStatus
-- Technically, doing the --only-download filtering only in this function is
-- not perfect. We could also prune the plan at an earlier stage, like it's
-- done with --only-dependencies. But...
-- * the benefit would be minimal (practically just avoiding to print the
-- "requires build" parts of the plan)
-- * we currently don't have easy access to the BuildStatus of packages
-- in the pruning phase
-- * we still have to check it here to avoid performing successive phases
| buildSettingOnlyDownload buildSettings = do
case pkgBuildStatus of
BuildStatusDownload ->
void $ waitAsyncPackageDownload verbosity downloadMap pkg
_ -> return ()
return $ BuildResult DocsNotTried TestsNotTried Nothing
| otherwise =
-- We rely on the 'BuildStatus' to decide which phase to start from:
case pkgBuildStatus of
BuildStatusDownload -> downloadPhase
BuildStatusUnpack tarball -> unpackTarballPhase tarball
BuildStatusRebuild srcdir status -> rebuildPhase status srcdir
-- TODO: perhaps re-nest the types to make these impossible
BuildStatusPreExisting{} -> unexpectedState
BuildStatusInstalled{} -> unexpectedState
BuildStatusUpToDate{} -> unexpectedState
where
unexpectedState = error "rebuildTarget: unexpected package status"
downloadPhase :: IO BuildResult
downloadPhase = do
downsrcloc <-
annotateFailureNoLog DownloadFailed $
waitAsyncPackageDownload verbosity downloadMap pkg
case downsrcloc of
DownloadedTarball tarball -> unpackTarballPhase tarball
-- TODO: [nice to have] git/darcs repos etc
unpackTarballPhase :: FilePath -> IO BuildResult
unpackTarballPhase tarball =
withTarballLocalDirectory
verbosity
distDirLayout
tarball
(packageId pkg)
(elabDistDirParams sharedPackageConfig pkg)
(elabBuildStyle pkg)
(elabPkgDescriptionOverride pkg)
$ case elabBuildStyle pkg of
BuildAndInstall -> buildAndInstall
BuildInplaceOnly{} -> buildInplace buildStatus
where
buildStatus = BuildStatusConfigure MonitorFirstRun
-- Note that this really is rebuild, not build. It can only happen for
-- 'BuildInplaceOnly' style packages. 'BuildAndInstall' style packages
-- would only start from download or unpack phases.
--
rebuildPhase :: BuildStatusRebuild -> FilePath -> IO BuildResult
rebuildPhase buildStatus srcdir =
assert
(isInplaceBuildStyle $ elabBuildStyle pkg)
buildInplace
buildStatus
srcdir
builddir
where
builddir =
distBuildDirectory
(elabDistDirParams sharedPackageConfig pkg)
buildAndInstall :: FilePath -> FilePath -> IO BuildResult
buildAndInstall srcdir builddir =
buildAndInstallUnpackedPackage
verbosity
distDirLayout
storeDirLayout
semaphoreName
buildSettings
registerLock
cacheLock
sharedPackageConfig
plan
rpkg
srcdir
builddir'
where
builddir' = makeRelative srcdir builddir
-- TODO: [nice to have] ^^ do this relative stuff better
buildInplace :: BuildStatusRebuild -> FilePath -> FilePath -> IO BuildResult
buildInplace buildStatus srcdir builddir =
-- TODO: [nice to have] use a relative build dir rather than absolute
buildInplaceUnpackedPackage
verbosity
distDirLayout
semaphoreName
buildSettings
registerLock
cacheLock
sharedPackageConfig
plan
rpkg
buildStatus
srcdir
builddir
-- TODO: [nice to have] do we need to use a with-style for the temp
-- files for downloading http packages, or are we going to cache them
-- persistently?
-- | Given the current 'InstallPlan' and 'BuildStatusMap', select all the
-- packages we have to download and fork off an async action to download them.
-- We download them in dependency order so that the one's we'll need
-- first are the ones we will start downloading first.
--
-- The body action is passed a map from those packages (identified by their
-- location) to a completion var for that package. So the body action should
-- lookup the location and use 'waitAsyncPackageDownload' to get the result.
asyncDownloadPackages
:: Verbosity
-> ((RepoContext -> IO a) -> IO a)
-> ElaboratedInstallPlan
-> BuildStatusMap
-> (AsyncFetchMap -> IO a)
-> IO a
asyncDownloadPackages verbosity withRepoCtx installPlan pkgsBuildStatus body
| null pkgsToDownload = body Map.empty
| otherwise = withRepoCtx $ \repoctx ->
asyncFetchPackages
verbosity
repoctx
pkgsToDownload
body
where
pkgsToDownload :: [PackageLocation (Maybe FilePath)]
pkgsToDownload =
ordNub $
[ elabPkgSourceLocation elab
| InstallPlan.Configured elab <-
InstallPlan.reverseTopologicalOrder installPlan
, let uid = installedUnitId elab
pkgBuildStatus = Map.findWithDefault (error "asyncDownloadPackages") uid pkgsBuildStatus
, BuildStatusDownload <- [pkgBuildStatus]
]
-- | Check if a package needs downloading, and if so expect to find a download
-- in progress in the given 'AsyncFetchMap' and wait on it to finish.
waitAsyncPackageDownload
:: Verbosity
-> AsyncFetchMap
-> ElaboratedConfiguredPackage
-> IO DownloadedSourceLocation
waitAsyncPackageDownload verbosity downloadMap elab = do
pkgloc <-
waitAsyncFetchPackage
verbosity
downloadMap
(elabPkgSourceLocation elab)
case downloadedSourceLocation pkgloc of
Just loc -> return loc
Nothing -> fail "waitAsyncPackageDownload: unexpected source location"
data DownloadedSourceLocation = DownloadedTarball FilePath
-- TODO: [nice to have] git/darcs repos etc
downloadedSourceLocation
:: PackageLocation FilePath
-> Maybe DownloadedSourceLocation
downloadedSourceLocation pkgloc =
case pkgloc of
RemoteTarballPackage _ tarball -> Just (DownloadedTarball tarball)
RepoTarballPackage _ _ tarball -> Just (DownloadedTarball tarball)
_ -> Nothing
-- | Ensure that the package is unpacked in an appropriate directory, either
-- a temporary one or a persistent one under the shared dist directory.
withTarballLocalDirectory
:: Verbosity
-> DistDirLayout
-> FilePath
-> PackageId
-> DistDirParams
-> BuildStyle