-
Notifications
You must be signed in to change notification settings - Fork 696
/
ProjectOrchestration.hs
1504 lines (1374 loc) · 54.8 KB
/
ProjectOrchestration.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 #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE ViewPatterns #-}
-- | This module deals with building and incrementally rebuilding a collection
-- of packages. It is what backs the @cabal build@ and @configure@ commands,
-- as well as being a core part of @run@, @test@, @bench@ and others.
--
-- The primary thing is in fact rebuilding (and trying to make that quick by
-- not redoing unnecessary work), so building from scratch is just a special
-- case.
--
-- The build process and the code can be understood by breaking it down into
-- three major parts:
--
-- * The 'ElaboratedInstallPlan' type
--
-- * The \"what to do\" phase, where we look at the all input configuration
-- (project files, .cabal files, command line etc) and produce a detailed
-- plan of what to do -- the 'ElaboratedInstallPlan'.
--
-- * The \"do it\" phase, where we take the 'ElaboratedInstallPlan' and we
-- re-execute it.
--
-- As far as possible, the \"what to do\" phase embodies all the policy, leaving
-- the \"do it\" phase policy free. The first phase contains more of the
-- complicated logic, but it is contained in code that is either pure or just
-- has read effects (except cache updates). Then the second phase does all the
-- actions to build packages, but as far as possible it just follows the
-- instructions and avoids any logic for deciding what to do (apart from
-- recompilation avoidance in executing the plan).
--
-- This division helps us keep the code under control, making it easier to
-- understand, test and debug. So when you are extending these modules, please
-- think about which parts of your change belong in which part. It is
-- perfectly ok to extend the description of what to do (i.e. the
-- 'ElaboratedInstallPlan') if that helps keep the policy decisions in the
-- first phase. Also, the second phase does not have direct access to any of
-- the input configuration anyway; all the information has to flow via the
-- 'ElaboratedInstallPlan'.
module Distribution.Client.ProjectOrchestration
( -- * Discovery phase: what is in the project?
CurrentCommand (..)
, establishProjectBaseContext
, establishProjectBaseContextWithRoot
, ProjectBaseContext (..)
, BuildTimeSettings (..)
, commandLineFlagsToProjectConfig
-- * Pre-build phase: decide what to do.
, withInstallPlan
, runProjectPreBuildPhase
, ProjectBuildContext (..)
-- ** Selecting what targets we mean
, readTargetSelectors
, reportTargetSelectorProblems
, resolveTargets
, TargetsMap
, allTargetSelectors
, uniqueTargetSelectors
, TargetSelector (..)
, TargetImplicitCwd (..)
, PackageId
, AvailableTarget (..)
, AvailableTargetStatus (..)
, TargetRequested (..)
, ComponentName (..)
, ComponentKind (..)
, ComponentTarget (..)
, SubComponentTarget (..)
, selectComponentTargetBasic
, distinctTargetComponents
-- ** Utils for selecting targets
, filterTargetsKind
, filterTargetsKindWith
, selectBuildableTargets
, selectBuildableTargetsWith
, selectBuildableTargets'
, selectBuildableTargetsWith'
, forgetTargetsDetail
-- ** Adjusting the plan
, pruneInstallPlanToTargets
, TargetAction (..)
, pruneInstallPlanToDependencies
, CannotPruneDependencies (..)
, printPlan
-- * Build phase: now do it.
, runProjectBuildPhase
-- * Post build actions
, runProjectPostBuildPhase
, dieOnBuildFailures
-- * Dummy projects
, establishDummyProjectBaseContext
, establishDummyDistDirLayout
) where
import Distribution.Client.Compat.Prelude
import Distribution.Compat.Directory
( makeAbsolute
)
import Prelude ()
import Distribution.Client.ProjectBuilding
import Distribution.Client.ProjectConfig
import Distribution.Client.ProjectPlanOutput
import Distribution.Client.ProjectPlanning hiding
( pruneInstallPlanToTargets
)
import qualified Distribution.Client.ProjectPlanning as ProjectPlanning
( pruneInstallPlanToTargets
)
import Distribution.Client.ProjectPlanning.Types
import Distribution.Client.DistDirLayout
import qualified Distribution.Client.InstallPlan as InstallPlan
import Distribution.Client.TargetProblem
( TargetProblem (..)
)
import Distribution.Client.TargetSelector
( ComponentKind (..)
, TargetImplicitCwd (..)
, TargetSelector (..)
, componentKind
, readTargetSelectors
, reportTargetSelectorProblems
)
import Distribution.Client.Types
( DocsResult (..)
, GenericReadyPackage (..)
, PackageLocation (..)
, PackageSpecifier (..)
, SourcePackageDb (..)
, TestsResult (..)
, UnresolvedSourcePackage
, WriteGhcEnvironmentFilesPolicy (..)
)
import Distribution.Solver.Types.PackageIndex
( lookupPackageName
)
import Distribution.Client.BuildReports.Anonymous (cabalInstallID)
import qualified Distribution.Client.BuildReports.Anonymous as BuildReports
import qualified Distribution.Client.BuildReports.Storage as BuildReports
( storeLocal
)
import Distribution.Client.HttpUtils
import Distribution.Client.Setup hiding (packageName)
import Distribution.Compiler
( CompilerFlavor (GHC)
)
import Distribution.Types.ComponentName
( componentNameString
)
import Distribution.Types.InstalledPackageInfo
( InstalledPackageInfo
)
import Distribution.Types.UnqualComponentName
( UnqualComponentName
, packageNameToUnqualComponentName
)
import Distribution.Solver.Types.OptionalStanza
import Control.Exception (assert)
import qualified Data.List.NonEmpty as NE
import qualified Data.Map as Map
import qualified Data.Set as Set
import Distribution.Client.Errors
import Distribution.Package
import Distribution.Simple.Command (commandShowOptions)
import Distribution.Simple.Compiler
( OptimisationLevel (..)
, compilerCompatVersion
, compilerId
, compilerInfo
, showCompilerId
)
import Distribution.Simple.Configure (computeEffectiveProfiling)
import Distribution.Simple.Flag
( flagToMaybe
, fromFlagOrDefault
)
import Distribution.Simple.LocalBuildInfo
( ComponentName (..)
, pkgComponents
)
import Distribution.Simple.PackageIndex (InstalledPackageIndex)
import qualified Distribution.Simple.Setup as Setup
import Distribution.Simple.Utils
( createDirectoryIfMissingVerbose
, debugNoWrap
, dieWithException
, notice
, noticeNoWrap
, ordNub
, warn
)
import Distribution.System
( Platform (Platform)
)
import Distribution.Types.Flag
( FlagAssignment
, diffFlagAssignment
, showFlagAssignment
)
import Distribution.Utils.NubList
( fromNubList
)
import Distribution.Utils.Path (makeSymbolicPath)
import Distribution.Verbosity
import Distribution.Version
( mkVersion
)
#ifdef MIN_VERSION_unix
import System.Posix.Signals (sigKILL, sigSEGV)
#endif
-- | Tracks what command is being executed, because we need to hide this somewhere
-- for cases that need special handling (usually for error reporting).
data CurrentCommand = InstallCommand | HaddockCommand | BuildCommand | ReplCommand | OtherCommand
deriving (Show, Eq)
-- | This holds the context of a project prior to solving: the content of the
-- @cabal.project@, @cabal/config@ and all the local package @.cabal@ files.
data ProjectBaseContext = ProjectBaseContext
{ distDirLayout :: DistDirLayout
, cabalDirLayout :: CabalDirLayout
, projectConfig :: ProjectConfig
, localPackages :: [PackageSpecifier UnresolvedSourcePackage]
-- ^ Note: these are all the packages mentioned in the project configuration.
-- Whether or not they will be considered local to the project will be decided
-- by `shouldBeLocal` in ProjectPlanning.
, buildSettings :: BuildTimeSettings
, currentCommand :: CurrentCommand
, installedPackages :: Maybe InstalledPackageIndex
}
establishProjectBaseContext
:: Verbosity
-> ProjectConfig
-> CurrentCommand
-> IO ProjectBaseContext
establishProjectBaseContext verbosity cliConfig currentCommand = do
projectRoot <- either throwIO return =<< findProjectRoot verbosity mprojectDir mprojectFile
establishProjectBaseContextWithRoot verbosity cliConfig projectRoot currentCommand
where
mprojectDir = Setup.flagToMaybe projectConfigProjectDir
mprojectFile = Setup.flagToMaybe projectConfigProjectFile
ProjectConfigShared{projectConfigProjectDir, projectConfigProjectFile} = projectConfigShared cliConfig
-- | Like 'establishProjectBaseContext' but doesn't search for project root.
establishProjectBaseContextWithRoot
:: Verbosity
-> ProjectConfig
-> ProjectRoot
-> CurrentCommand
-> IO ProjectBaseContext
establishProjectBaseContextWithRoot verbosity cliConfig projectRoot currentCommand = do
let haddockOutputDir = flagToMaybe (packageConfigHaddockOutputDir (projectConfigLocalPackages cliConfig))
let distDirLayout = defaultDistDirLayout projectRoot mdistDirectory haddockOutputDir
httpTransport <-
configureTransport
verbosity
(fromNubList . projectConfigProgPathExtra $ projectConfigShared cliConfig)
(flagToMaybe . projectConfigHttpTransport $ projectConfigBuildOnly cliConfig)
(projectConfig, localPackages) <-
rebuildProjectConfig
verbosity
httpTransport
distDirLayout
cliConfig
let ProjectConfigBuildOnly
{ projectConfigLogsDir
} = projectConfigBuildOnly projectConfig
ProjectConfigShared
{ projectConfigStoreDir
} = projectConfigShared projectConfig
mlogsDir = Setup.flagToMaybe projectConfigLogsDir
mstoreDir <-
sequenceA $
makeAbsolute
<$> Setup.flagToMaybe projectConfigStoreDir
cabalDirLayout <- mkCabalDirLayout mstoreDir mlogsDir
let buildSettings =
resolveBuildTimeSettings
verbosity
cabalDirLayout
projectConfig
-- https://github.com/haskell/cabal/issues/6013
when (null (projectPackages projectConfig) && null (projectPackagesOptional projectConfig)) $
warn verbosity "There are no packages or optional-packages in the project"
return
ProjectBaseContext
{ distDirLayout
, cabalDirLayout
, projectConfig
, localPackages
, buildSettings
, currentCommand
, installedPackages
}
where
mdistDirectory = Setup.flagToMaybe projectConfigDistDir
ProjectConfigShared{projectConfigDistDir} = projectConfigShared cliConfig
installedPackages = Nothing
-- | This holds the context between the pre-build, build and post-build phases.
data ProjectBuildContext = ProjectBuildContext
{ elaboratedPlanOriginal :: ElaboratedInstallPlan
-- ^ This is the improved plan, before we select a plan subset based on
-- the build targets, and before we do the dry-run. So this contains
-- all packages in the project.
, elaboratedPlanToExecute :: ElaboratedInstallPlan
-- ^ This is the 'elaboratedPlanOriginal' after we select a plan subset
-- and do the dry-run phase to find out what is up-to or out-of date.
-- This is the plan that will be executed during the build phase. So
-- this contains only a subset of packages in the project.
, elaboratedShared :: ElaboratedSharedConfig
-- ^ The part of the install plan that's shared between all packages in
-- the plan. This does not change between the two plan variants above,
-- so there is just the one copy.
, pkgsBuildStatus :: BuildStatusMap
-- ^ The result of the dry-run phase. This tells us about each member of
-- the 'elaboratedPlanToExecute'.
, targetsMap :: TargetsMap
-- ^ The targets selected by @selectPlanSubset@. This is useful eg. in
-- CmdRun, where we need a valid target to execute.
}
-- | Pre-build phase: decide what to do.
withInstallPlan
:: Verbosity
-> ProjectBaseContext
-> (ElaboratedInstallPlan -> ElaboratedSharedConfig -> IO a)
-> IO a
withInstallPlan
verbosity
ProjectBaseContext
{ distDirLayout
, cabalDirLayout
, projectConfig
, localPackages
, installedPackages
}
action = do
-- Take the project configuration and make a plan for how to build
-- everything in the project. This is independent of any specific targets
-- the user has asked for.
--
(elaboratedPlan, _, elaboratedShared, _, _) <-
rebuildInstallPlan
verbosity
distDirLayout
cabalDirLayout
projectConfig
localPackages
installedPackages
action elaboratedPlan elaboratedShared
runProjectPreBuildPhase
:: Verbosity
-> ProjectBaseContext
-> (ElaboratedInstallPlan -> IO (ElaboratedInstallPlan, TargetsMap))
-> IO ProjectBuildContext
runProjectPreBuildPhase
verbosity
ProjectBaseContext
{ distDirLayout
, cabalDirLayout
, projectConfig
, localPackages
, installedPackages
}
selectPlanSubset = do
-- Take the project configuration and make a plan for how to build
-- everything in the project. This is independent of any specific targets
-- the user has asked for.
--
(elaboratedPlan, _, elaboratedShared, _, _) <-
rebuildInstallPlan
verbosity
distDirLayout
cabalDirLayout
projectConfig
localPackages
installedPackages
-- The plan for what to do is represented by an 'ElaboratedInstallPlan'
-- Now given the specific targets the user has asked for, decide
-- which bits of the plan we will want to execute.
--
(elaboratedPlan', targets) <- selectPlanSubset elaboratedPlan
-- Check which packages need rebuilding.
-- This also gives us more accurate reasons for the --dry-run output.
--
pkgsBuildStatus <-
rebuildTargetsDryRun
distDirLayout
elaboratedShared
elaboratedPlan'
-- Improve the plan by marking up-to-date packages as installed.
--
let elaboratedPlan'' =
improveInstallPlanWithUpToDatePackages
pkgsBuildStatus
elaboratedPlan'
debugNoWrap verbosity (InstallPlan.showInstallPlan elaboratedPlan'')
return
ProjectBuildContext
{ elaboratedPlanOriginal = elaboratedPlan
, elaboratedPlanToExecute = elaboratedPlan''
, elaboratedShared
, pkgsBuildStatus
, targetsMap = targets
}
-- | Build phase: now do it.
--
-- Execute all or parts of the description of what to do to build or
-- rebuild the various packages needed.
runProjectBuildPhase
:: Verbosity
-> ProjectBaseContext
-> ProjectBuildContext
-> IO BuildOutcomes
runProjectBuildPhase _ ProjectBaseContext{buildSettings} _
| buildSettingDryRun buildSettings =
return Map.empty
runProjectBuildPhase
verbosity
ProjectBaseContext{..}
ProjectBuildContext{..} =
fmap (Map.union (previousBuildOutcomes pkgsBuildStatus)) $
rebuildTargets
verbosity
projectConfig
distDirLayout
(cabalStoreDirLayout cabalDirLayout)
elaboratedPlanToExecute
elaboratedShared
pkgsBuildStatus
buildSettings
where
previousBuildOutcomes :: BuildStatusMap -> BuildOutcomes
previousBuildOutcomes =
Map.mapMaybe $ \status -> case status of
BuildStatusUpToDate buildSuccess -> Just (Right buildSuccess)
-- TODO: [nice to have] record build failures persistently
_ -> Nothing
-- | Post-build phase: various administrative tasks
--
-- Update bits of state based on the build outcomes and report any failures.
runProjectPostBuildPhase
:: Verbosity
-> ProjectBaseContext
-> ProjectBuildContext
-> BuildOutcomes
-> IO ()
runProjectPostBuildPhase _ ProjectBaseContext{buildSettings} _ _
| buildSettingDryRun buildSettings =
return ()
runProjectPostBuildPhase
verbosity
ProjectBaseContext{..}
bc@ProjectBuildContext{..}
buildOutcomes = do
-- Update other build artefacts
-- TODO: currently none, but could include:
-- - bin symlinks/wrappers
-- - haddock/hoogle/ctags indexes
-- - delete stale lib registrations
-- - delete stale package dirs
postBuildStatus <-
updatePostBuildProjectStatus
verbosity
distDirLayout
elaboratedPlanOriginal
pkgsBuildStatus
buildOutcomes
-- Write the .ghc.environment file (if allowed by the env file write policy).
let writeGhcEnvFilesPolicy =
projectConfigWriteGhcEnvironmentFilesPolicy . projectConfigShared $
projectConfig
shouldWriteGhcEnvironment :: Bool
shouldWriteGhcEnvironment =
case fromFlagOrDefault
NeverWriteGhcEnvironmentFiles
writeGhcEnvFilesPolicy of
AlwaysWriteGhcEnvironmentFiles -> True
NeverWriteGhcEnvironmentFiles -> False
WriteGhcEnvironmentFilesOnlyForGhc844AndNewer ->
let compiler = pkgConfigCompiler elaboratedShared
ghcCompatVersion = compilerCompatVersion GHC compiler
in maybe False (>= mkVersion [8, 4, 4]) ghcCompatVersion
when shouldWriteGhcEnvironment $
void $
writePlanGhcEnvironment
(distProjectRootDirectory distDirLayout)
elaboratedPlanOriginal
elaboratedShared
postBuildStatus
-- Write the build reports
writeBuildReports buildSettings bc elaboratedPlanToExecute buildOutcomes
-- Finally if there were any build failures then report them and throw
-- an exception to terminate the program
dieOnBuildFailures verbosity currentCommand elaboratedPlanToExecute buildOutcomes
-- Note that it is a deliberate design choice that the 'buildTargets' is
-- not passed to phase 1, and the various bits of input config is not
-- passed to phase 2.
--
-- We make the install plan without looking at the particular targets the
-- user asks us to build. The set of available things we can build is
-- discovered from the env and config and is used to make the install plan.
-- The targets just tell us which parts of the install plan to execute.
--
-- Conversely, executing the plan does not directly depend on any of the
-- input config. The bits that are needed (or better, the decisions based
-- on it) all go into the install plan.
-- Notionally, the 'BuildFlags' should be things that do not affect what
-- we build, just how we do it. These ones of course do
------------------------------------------------------------------------------
-- Taking targets into account, selecting what to build
--
-- | The set of components to build, represented as a mapping from 'UnitId's
-- to the 'ComponentTarget's within the unit that will be selected
-- (e.g. selected to build, test or repl).
--
-- Associated with each 'ComponentTarget' is the set of 'TargetSelector's that
-- matched this target. Typically this is exactly one, but in general it is
-- possible to for different selectors to match the same target. This extra
-- information is primarily to help make helpful error messages.
type TargetsMap = Map UnitId [(ComponentTarget, NonEmpty TargetSelector)]
-- | Get all target selectors.
allTargetSelectors :: TargetsMap -> [TargetSelector]
allTargetSelectors = concatMap (NE.toList . snd) . concat . Map.elems
-- | Get all unique target selectors.
uniqueTargetSelectors :: TargetsMap -> [TargetSelector]
uniqueTargetSelectors = ordNub . allTargetSelectors
-- | Given a set of 'TargetSelector's, resolve which 'UnitId's and
-- 'ComponentTarget's they ought to refer to.
--
-- The idea is that every user target identifies one or more roots in the
-- 'ElaboratedInstallPlan', which we will use to determine the closure
-- of what packages need to be built, dropping everything from the plan
-- that is unnecessary. This closure and pruning is done by
-- 'pruneInstallPlanToTargets' and this needs to be told the roots in terms
-- of 'UnitId's and the 'ComponentTarget's within those.
--
-- This means we first need to translate the 'TargetSelector's into the
-- 'UnitId's and 'ComponentTarget's. This translation has to be different for
-- the different command line commands, like @build@, @repl@ etc. For example
-- the command @build pkgfoo@ could select a different set of components in
-- pkgfoo than @repl pkgfoo@. The @build@ command would select any library and
-- all executables, whereas @repl@ would select the library or a single
-- executable. Furthermore, both of these examples could fail, and fail in
-- different ways and each needs to be able to produce helpful error messages.
--
-- So 'resolveTargets' takes two helpers: one to select the targets to be used
-- by user targets that refer to a whole package ('TargetPackage'), and
-- another to check user targets that refer to a component (or a module or
-- file within a component). These helpers can fail, and use their own error
-- type. Both helpers get given the 'AvailableTarget' info about the
-- component(s).
--
-- While commands vary quite a bit in their behaviour about which components to
-- select for a whole-package target, most commands have the same behaviour for
-- checking a user target that refers to a specific component. To help with
-- this commands can use 'selectComponentTargetBasic', either directly or as
-- a basis for their own @selectComponentTarget@ implementation.
resolveTargets
:: forall err
. ( forall k
. TargetSelector
-> [AvailableTarget k]
-> Either (TargetProblem err) [k]
)
-> ( forall k
. SubComponentTarget
-> AvailableTarget k
-> Either (TargetProblem err) k
)
-> ElaboratedInstallPlan
-> Maybe (SourcePackageDb)
-> [TargetSelector]
-> Either [TargetProblem err] TargetsMap
resolveTargets
selectPackageTargets
selectComponentTarget
installPlan
mPkgDb =
fmap mkTargetsMap
. either (Left . toList) Right
. checkErrors
. map (\ts -> (,) ts <$> checkTarget ts)
where
mkTargetsMap
:: [(TargetSelector, [(UnitId, ComponentTarget)])]
-> TargetsMap
mkTargetsMap targets =
Map.map nubComponentTargets $
Map.fromListWith
(<>)
[ (uid, [(ct, ts)])
| (ts, cts) <- targets
, (uid, ct) <- cts
]
AvailableTargetIndexes{..} = availableTargetIndexes installPlan
checkTarget :: TargetSelector -> Either (TargetProblem err) [(UnitId, ComponentTarget)]
-- We can ask to build any whole package, project-local or a dependency
checkTarget bt@(TargetPackage _ (ordNub -> [pkgid]) mkfilter)
| Just ats <-
fmap (maybe id filterTargetsKind mkfilter) $
Map.lookup pkgid availableTargetsByPackageId =
fmap (componentTargets WholeComponent) $
selectPackageTargets bt ats
| otherwise =
Left (TargetProblemNoSuchPackage pkgid)
checkTarget (TargetPackage _ pkgids _) =
error
( "TODO: add support for multiple packages in a directory. Got\n"
++ unlines (map prettyShow pkgids)
)
-- For the moment this error cannot happen here, because it gets
-- detected when the package config is being constructed. This case
-- will need handling properly when we do add support.
--
-- TODO: how should this use case play together with the
-- '--cabal-file' option of 'configure' which allows using multiple
-- .cabal files for a single package?
checkTarget bt@(TargetAllPackages mkfilter) =
fmap (componentTargets WholeComponent)
. selectPackageTargets bt
. maybe id filterTargetsKind mkfilter
. filter availableTargetLocalToProject
$ concat (Map.elems availableTargetsByPackageId)
checkTarget (TargetComponent pkgid cname subtarget)
| Just ats <-
Map.lookup
(pkgid, cname)
availableTargetsByPackageIdAndComponentName =
fmap (componentTargets subtarget) $
selectComponentTargets subtarget ats
| Map.member pkgid availableTargetsByPackageId =
Left (TargetProblemNoSuchComponent pkgid cname)
| otherwise =
Left (TargetProblemNoSuchPackage pkgid)
checkTarget (TargetComponentUnknown pkgname ecname subtarget)
| Just ats <- case ecname of
Left ucname ->
Map.lookup
(pkgname, ucname)
availableTargetsByPackageNameAndUnqualComponentName
Right cname ->
Map.lookup
(pkgname, cname)
availableTargetsByPackageNameAndComponentName =
fmap (componentTargets subtarget) $
selectComponentTargets subtarget ats
| Map.member pkgname availableTargetsByPackageName =
Left (TargetProblemUnknownComponent pkgname ecname)
| otherwise =
Left (TargetNotInProject pkgname)
checkTarget bt@(TargetPackageNamed pkgname mkfilter)
| Just ats <-
fmap (maybe id filterTargetsKind mkfilter) $
Map.lookup pkgname availableTargetsByPackageName =
fmap (componentTargets WholeComponent)
. selectPackageTargets bt
$ ats
| Just SourcePackageDb{packageIndex} <- mPkgDb
, let pkg = lookupPackageName packageIndex pkgname
, not (null pkg) =
Left (TargetAvailableInIndex pkgname)
| otherwise =
Left (TargetNotInProject pkgname)
componentTargets
:: SubComponentTarget
-> [(b, ComponentName)]
-> [(b, ComponentTarget)]
componentTargets subtarget =
map (fmap (\cname -> ComponentTarget cname subtarget))
selectComponentTargets
:: SubComponentTarget
-> [AvailableTarget k]
-> Either (TargetProblem err) [k]
selectComponentTargets subtarget =
either (Left . NE.head) Right
. checkErrors
. map (selectComponentTarget subtarget)
checkErrors :: [Either e a] -> Either (NonEmpty e) [a]
checkErrors =
(\(es, xs) -> case es of [] -> Right xs; (e : es') -> Left (e :| es'))
. partitionEithers
data AvailableTargetIndexes = AvailableTargetIndexes
{ availableTargetsByPackageIdAndComponentName
:: AvailableTargetsMap (PackageId, ComponentName)
, availableTargetsByPackageId
:: AvailableTargetsMap PackageId
, availableTargetsByPackageName
:: AvailableTargetsMap PackageName
, availableTargetsByPackageNameAndComponentName
:: AvailableTargetsMap (PackageName, ComponentName)
, availableTargetsByPackageNameAndUnqualComponentName
:: AvailableTargetsMap (PackageName, UnqualComponentName)
}
type AvailableTargetsMap k = Map k [AvailableTarget (UnitId, ComponentName)]
-- We define a bunch of indexes to help 'resolveTargets' with resolving
-- 'TargetSelector's to specific 'UnitId's.
--
-- They are all derived from the 'availableTargets' index.
-- The 'availableTargetsByPackageIdAndComponentName' is just that main index,
-- while the others are derived by re-grouping on the index key.
--
-- They are all constructed lazily because they are not necessarily all used.
--
availableTargetIndexes :: ElaboratedInstallPlan -> AvailableTargetIndexes
availableTargetIndexes installPlan = AvailableTargetIndexes{..}
where
availableTargetsByPackageIdAndComponentName
:: Map
(PackageId, ComponentName)
[AvailableTarget (UnitId, ComponentName)]
availableTargetsByPackageIdAndComponentName =
availableTargets installPlan
availableTargetsByPackageId
:: Map PackageId [AvailableTarget (UnitId, ComponentName)]
availableTargetsByPackageId =
Map.mapKeysWith
(++)
(\(pkgid, _cname) -> pkgid)
availableTargetsByPackageIdAndComponentName
`Map.union` availableTargetsEmptyPackages
availableTargetsByPackageName
:: Map PackageName [AvailableTarget (UnitId, ComponentName)]
availableTargetsByPackageName =
Map.mapKeysWith
(++)
packageName
availableTargetsByPackageId
availableTargetsByPackageNameAndComponentName
:: Map
(PackageName, ComponentName)
[AvailableTarget (UnitId, ComponentName)]
availableTargetsByPackageNameAndComponentName =
Map.mapKeysWith
(++)
(\(pkgid, cname) -> (packageName pkgid, cname))
availableTargetsByPackageIdAndComponentName
availableTargetsByPackageNameAndUnqualComponentName
:: Map
(PackageName, UnqualComponentName)
[AvailableTarget (UnitId, ComponentName)]
availableTargetsByPackageNameAndUnqualComponentName =
Map.mapKeysWith
(++)
( \(pkgid, cname) ->
let pname = packageName pkgid
cname' = unqualComponentName pname cname
in (pname, cname')
)
availableTargetsByPackageIdAndComponentName
where
unqualComponentName
:: PackageName -> ComponentName -> UnqualComponentName
unqualComponentName pkgname =
fromMaybe (packageNameToUnqualComponentName pkgname)
. componentNameString
-- Add in all the empty packages. These do not appear in the
-- availableTargetsByComponent map, since that only contains
-- components, so packages with no components are invisible from
-- that perspective. The empty packages need to be there for
-- proper error reporting, so users can select the empty package
-- and then we can report that it is empty, otherwise we falsely
-- report there is no such package at all.
availableTargetsEmptyPackages =
Map.fromList
[ (packageId pkg, [])
| InstallPlan.Configured pkg <- InstallPlan.toList installPlan
, case elabPkgOrComp pkg of
ElabComponent _ -> False
ElabPackage _ -> null (pkgComponents (elabPkgDescription pkg))
]
-- TODO: [research required] what if the solution has multiple
-- versions of this package?
-- e.g. due to setup deps or due to multiple independent sets
-- of packages being built (e.g. ghc + ghcjs in a project)
filterTargetsKind :: ComponentKind -> [AvailableTarget k] -> [AvailableTarget k]
filterTargetsKind ckind = filterTargetsKindWith (== ckind)
filterTargetsKindWith
:: (ComponentKind -> Bool)
-> [AvailableTarget k]
-> [AvailableTarget k]
filterTargetsKindWith p ts =
[ t | t@(AvailableTarget _ cname _ _) <- ts, p (componentKind cname)
]
selectBuildableTargets :: [AvailableTarget k] -> [k]
selectBuildableTargets = selectBuildableTargetsWith (const True)
zipBuildableTargetsWith
:: (TargetRequested -> Bool)
-> [AvailableTarget k]
-> [(k, AvailableTarget k)]
zipBuildableTargetsWith p ts =
[(k, t) | t@(AvailableTarget _ _ (TargetBuildable k req) _) <- ts, p req]
selectBuildableTargetsWith
:: (TargetRequested -> Bool)
-> [AvailableTarget k]
-> [k]
selectBuildableTargetsWith p = map fst . zipBuildableTargetsWith p
selectBuildableTargets' :: [AvailableTarget k] -> ([k], [AvailableTarget ()])
selectBuildableTargets' = selectBuildableTargetsWith' (const True)
selectBuildableTargetsWith'
:: (TargetRequested -> Bool)
-> [AvailableTarget k]
-> ([k], [AvailableTarget ()])
selectBuildableTargetsWith' p =
(fmap . map) forgetTargetDetail . unzip . zipBuildableTargetsWith p
forgetTargetDetail :: AvailableTarget k -> AvailableTarget ()
forgetTargetDetail = fmap (const ())
forgetTargetsDetail :: [AvailableTarget k] -> [AvailableTarget ()]
forgetTargetsDetail = map forgetTargetDetail
-- | A basic @selectComponentTarget@ implementation to use or pass to
-- 'resolveTargets', that does the basic checks that the component is
-- buildable and isn't a test suite or benchmark that is disabled. This
-- can also be used to do these basic checks as part of a custom impl that
selectComponentTargetBasic
:: SubComponentTarget
-> AvailableTarget k
-> Either (TargetProblem a) k
selectComponentTargetBasic
subtarget
AvailableTarget
{ availableTargetPackageId = pkgid
, availableTargetComponentName = cname
, availableTargetStatus
} =
case availableTargetStatus of
TargetDisabledByUser ->
Left (TargetOptionalStanzaDisabledByUser pkgid cname subtarget)
TargetDisabledBySolver ->
Left (TargetOptionalStanzaDisabledBySolver pkgid cname subtarget)
TargetNotLocal ->
Left (TargetComponentNotProjectLocal pkgid cname subtarget)
TargetNotBuildable ->
Left (TargetComponentNotBuildable pkgid cname subtarget)
TargetBuildable targetKey _ ->
Right targetKey
-- | Wrapper around 'ProjectPlanning.pruneInstallPlanToTargets' that adjusts
-- for the extra unneeded info in the 'TargetsMap'.
pruneInstallPlanToTargets
:: TargetAction
-> TargetsMap
-> ElaboratedInstallPlan
-> ElaboratedInstallPlan
pruneInstallPlanToTargets targetActionType targetsMap elaboratedPlan =
assert (Map.size targetsMap > 0) $
ProjectPlanning.pruneInstallPlanToTargets
targetActionType
(Map.map (map fst) targetsMap)
elaboratedPlan
-- | Utility used by repl and run to check if the targets spans multiple
-- components, since those commands do not support multiple components.
distinctTargetComponents :: TargetsMap -> Set.Set (UnitId, ComponentName)
distinctTargetComponents targetsMap =
Set.fromList
[ (uid, cname)
| (uid, cts) <- Map.toList targetsMap
, (ComponentTarget cname _, _) <- cts
]
------------------------------------------------------------------------------
-- Displaying what we plan to do
--
-- | Print a user-oriented presentation of the install plan, indicating what
-- will be built.
printPlan
:: Verbosity
-> ProjectBaseContext
-> ProjectBuildContext
-> IO ()
printPlan
verbosity
ProjectBaseContext
{ buildSettings = BuildTimeSettings{buildSettingDryRun, buildSettingKeepTempFiles}
, projectConfig =
ProjectConfig
{ projectConfigAllPackages =
PackageConfig{packageConfigOptimization = globalOptimization}
, projectConfigLocalPackages =
PackageConfig{packageConfigOptimization = localOptimization}
}
, currentCommand
}
ProjectBuildContext
{ elaboratedPlanToExecute = elaboratedPlan
, elaboratedShared
, pkgsBuildStatus
}
| null pkgs && currentCommand == BuildCommand =
notice verbosity "Up to date"
| not (null pkgs) =
noticeNoWrap verbosity $
unlines $
( showBuildProfile
++ "In order, the following "
++ wouldWill
++ " be built"
++ ifNormal " (use -v for more details)"
++ ":"
)
: map showPkgAndReason pkgs
| otherwise = return ()
where
pkgs = InstallPlan.executionOrder elaboratedPlan
ifVerbose s
| verbosity >= verbose = s
| otherwise = ""
ifNormal s
| verbosity >= verbose = ""
| otherwise = s
wouldWill
| buildSettingDryRun = "would"
| otherwise = "will"
showPkgAndReason :: ElaboratedReadyPackage -> String
showPkgAndReason (ReadyPackage elab) =
unwords $
filter (not . null) $
[ " -"
, if verbosity >= deafening
then prettyShow (installedUnitId elab)
else prettyShow (packageId elab)