-
Notifications
You must be signed in to change notification settings - Fork 849
Expand file tree
/
Copy pathExecutePackage.hs
More file actions
1698 lines (1627 loc) · 67.5 KB
/
Copy pathExecutePackage.hs
File metadata and controls
1698 lines (1627 loc) · 67.5 KB
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 NoImplicitPrelude #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE OverloadedRecordDot #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
{-|
Module : Stack.Build.ExecutePackage
Description : Perform a build.
License : BSD-3-Clause
Perform a build.
-}
module Stack.Build.ExecutePackage
( singleBuild
, singleTest
, singleBench
, componentTarget
, componentEnableTests
, componentEnableBenchmarks
, dispatchBuildOpts
-- * Backpack helpers (exported for testing)
, findGhcPkgId
, mkInstantiateWithOpts
) where
import Control.Concurrent.Execute
( ActionContext (..), ActionId (..) )
import Control.Monad.Extra ( whenJust )
import qualified Data.ByteString as S
import qualified Data.ByteString.Char8 as S8
import qualified Data.ByteString.Lazy as BL
import Conduit ( runConduitRes )
import qualified Data.Conduit.Filesystem as CF
import qualified Data.Conduit.List as CL
import Data.Conduit.Process.Typed ( createSource )
import qualified Data.Conduit.Text as CT
import qualified Data.List as L
import qualified Data.List.NonEmpty as NE
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import qualified Data.Text as T
import Distribution.ModuleName ( ModuleName )
import qualified Distribution.PackageDescription as C
import Distribution.System ( OS (..), Platform (..) )
import qualified Distribution.Text as C
import Distribution.Types.MungedPackageName
( encodeCompatPackageName )
import Path
( (</>), addExtension, filename, isProperPrefixOf, parent
, parseRelDir, parseRelFile, stripProperPrefix
)
import Path.Extra ( toFilePathNoTrailingSep )
import Path.IO
( copyFile, doesFileExist, ensureDir, ignoringAbsence
, removeDirRecur, removeFile
)
import RIO.NonEmpty ( nonEmpty )
import RIO.Process
( HasProcessContext, byteStringInput, findExecutable
, getStderr, getStdout, inherit, modifyEnvVars, proc
, setStderr, setStdin, setStdout, showProcessArgDebug
, useHandleOpen, waitExitCode, withModifyEnvVars
, withProcessWait, withWorkingDir
)
import Stack.Build.ConstructPlan ( shouldSplitComponents )
import Stack.Build.Cache
( TestStatus (..), deleteCaches, getTestStatus
, markExeInstalled, markExeNotInstalled, readPrecompiledCache
, setTestStatus, tryGetCabalMod, tryGetConfigCache
, tryGetPackageProjectRoot, tryGetSetupConfigMod
, writeBuildCache, writeCabalMod, writeConfigCache
, writeFlagCache, writePrecompiledCache
, writePackageProjectRoot, writeSetupConfigMod
)
import Stack.Build.ExecuteEnv
( ExcludeTHLoading (..), ExecuteEnv (..), KeepOutputOpen (..)
, OutputType (..), withSingleContext
)
import Stack.Build.TestSuiteTimeout
( forceKill, prepareForEscalation, terminateGracefully )
import Stack.Build.Source ( addUnlistedToBuildCache )
import Stack.Config.ConfigureScript ( ensureConfigureScript )
import Stack.ConfigureOpts
( configureOptsFromBase, renderConfigureOpts )
import Stack.Constants
( bindirSuffix, compilerOptionsCabalFlag, testGhcEnvRelFile )
import Stack.Constants.Config
( distDirFromDir, distRelativeDir, hpcDirFromDir
, hpcRelativeDir, setupConfigFromDir
)
import Stack.Coverage ( generateHpcReport, updateTixFile )
import Stack.GhcPkg ( ghcPkg, ghcPkgPathEnvVar, unregisterGhcPkgIds )
import Stack.Package
( buildLogPath, buildableExes, buildableSubLibs
, hasBuildableMainLibrary, hasIntraPackageDeps
)
import Stack.PackageDump ( conduitDumpPackage, ghcPkgDescribe )
import Stack.Prelude
import Stack.Types.Build ( RunCabalWithArgs )
import Stack.Types.Build.Exception
( BuildException (..), BuildPrettyException (..) )
import Stack.Types.BuildConfig
( BuildConfig (..), HasBuildConfig (..), configFileRootL )
import Stack.Types.BuildOpts
( BenchmarkOpts (..), BuildOpts (..), HaddockOpts (..)
, TestOpts (..)
)
import Stack.Types.BuildOptsCLI ( BuildOptsCLI (..) )
import Stack.Types.Cache
( ConfigCache (..), ConfigCacheType (..)
, PrecompiledCache (..)
)
import qualified Stack.Types.Cache as ConfigCache ( ConfigCache (..) )
import Stack.Types.CompCollection
( collectionKeyValueList, collectionLookup
, foldComponentToAnotherCollection, getBuildableListText
)
import Stack.Types.Compiler
( WhichCompiler (..), whichCompiler, whichCompilerL )
import Stack.Types.CompilerPaths
( CompilerPaths (..), GhcPkgExe (..), HasCompiler (..)
, cpWhich, getGhcPkgExe
)
import qualified Stack.Types.Component as Component
import Stack.Types.ComponentUtils
( StackUnqualCompName, toCabalName, unqualCompToString
, unqualCompToText
)
import Stack.Types.Config ( Config (..), HasConfig (..) )
import Stack.Types.ConfigureOpts
( BaseConfigOpts (..), ConfigureOpts (..) )
import Stack.Types.Curator ( Curator (..) )
import Stack.Types.DumpPackage ( DumpPackage (..) )
import Stack.Types.EnvConfig
( EnvConfig (..), HasEnvConfig (..), actualCompilerVersionL
, appropriateGhcColorFlag
)
import Stack.Types.EnvSettings ( EnvSettings (..) )
import Stack.Types.GhcPkgId
( GhcPkgId, ghcPkgIdString, ghcPkgIdToText )
import Stack.Types.GlobalOpts ( GlobalOpts (..) )
import Stack.Types.Installed
( InstallLocation (..), Installed (..), InstalledMap
, InstalledLibraryInfo (..), simpleInstalledLib
)
import Stack.Types.IsMutable ( IsMutable (..) )
import Stack.Types.NamedComponent
( NamedComponent (..), exeComponents, isCBench, isCTest
, renderComponent
)
import Stack.Types.Package
( LocalPackage (..), Package (..), installedPackageToGhcPkgId
, runMemoizedWith, toCabalMungedPackageName
)
import Stack.Types.PackageFile ( PackageWarning (..) )
import Stack.Types.Plan
( ComponentKey (..), Task (..), TaskConfigOpts (..)
, TaskType (..), componentKeyPkgName, taskIsTarget
, taskLocation, taskProvides, taskTargetIsMutable
, taskTypePackageIdentifier
)
import Stack.Types.Runner ( HasRunner, globalOptsL )
import Stack.Types.SourceMap ( SourceMap (..) )
import System.IO.Error ( isDoesNotExistError )
import System.PosixCompat.Files
( createLink, getFileStatus, modificationTime )
import System.Random ( randomIO )
import System.Semaphore
( ServerSemaphore, clientSemaphoreName, semaphoreIdentifier
, serverClientSemaphore
)
-- | Generate the t'ConfigCache' value.
getConfigCache ::
HasEnvConfig env
=> ExecuteEnv
-> Task
-> InstalledMap
-> Bool
-> Bool
-> RIO env (Map MungedPackageId GhcPkgId, ConfigCache)
getConfigCache ee task installedMap enableTest enableBench = do
let extra =
-- We enable tests if the test suite dependencies are already
-- installed, so that we avoid unnecessary recompilation based on
-- cabal_macros.h changes when switching between 'stack build' and
-- 'stack test'. See:
-- https://github.com/commercialhaskell/stack/issues/805
case task.taskType of
TTLocalMutable _ ->
-- FIXME: make this work with exact-configuration.
-- Not sure how to plumb the info atm. See
-- https://github.com/commercialhaskell/stack/issues/2049
[ "--enable-tests" | enableTest] ++
[ "--enable-benchmarks" | enableBench]
TTRemotePackage{} -> []
idMap <- liftIO $ readTVarIO ee.ghcPkgIds
let getMissing ident =
case Map.lookup ident idMap of
Nothing
-- Expect to instead find it in installedMap if it's
-- an initialBuildSteps target.
| ee.buildOptsCLI.initialBuildSteps && taskIsTarget task
, Just (_, installed) <- Map.lookup (pkgName ident) installedMap
-> pure $ installedPackageToGhcPkgId ident installed
Just installed -> pure $ installedPackageToGhcPkgId ident installed
_ -> throwM $ PackageIdMissingBug ident
let cOpts = task.configOpts
missingMapList <- traverse getMissing $ toList cOpts.missing
let pcOpts = cOpts.pkgConfigOpts
missing' = Map.unions missingMapList
-- Historically the leftermost was missing' for union preference in case of
-- collision for the return here. But unifying things with configureOpts
-- where it was the opposite resulted in this. It doesn't seem to make any
-- difference anyway.
allDeps = Map.union missing' task.present
configureOpts' = configureOptsFromBase
cOpts.envConfig
cOpts.baseConfigOpts
allDeps
cOpts.isLocalNonExtraDep
cOpts.isMutable
pcOpts
instWithOpts =
mkInstantiateWithOpts task.backpackInstEntries allDeps
configureOpts = configureOpts'
{ nonPathRelated =
configureOpts'.nonPathRelated
++ map T.unpack extra
++ instWithOpts
}
deps = Set.fromList $ Map.elems missing' ++ Map.elems task.present
components = case task.taskType of
TTLocalMutable lp ->
Set.map (encodeUtf8 . renderComponent) lp.components
TTRemotePackage{} -> Set.empty
cache = ConfigCache
{ configureOpts
, deps
, components
, buildHaddocks = task.buildHaddocks
, pkgSrc = task.cachePkgSrc
, pathEnvVar = ee.pathEnvVar
}
pure (allDeps, cache)
-- | Look up the 'GhcPkgId' of a package's main library by its 'PackageName' in
-- a dependency map keyed by 'MungedPackageId'. Used to resolve implementing
-- packages for Backpack @--instantiate-with@ flags. Only matches the main
-- library; sublibrary entries (LSubLibName) are ignored.
findGhcPkgId ::
Map MungedPackageId GhcPkgId
-> PackageName
-> Maybe GhcPkgId
findGhcPkgId depsMap pn =
case [ gid
| (MungedPackageId (MungedPackageName n LMainLibName) _, gid)
<- Map.toList depsMap
, n == pn
] of
(gid:_) -> Just gid
[] -> Nothing
-- | Generate @--instantiate-with@ configure flags for CInst (Backpack
-- instantiation) tasks. Each entry maps a signature name to an implementing
-- module identified by its package's 'GhcPkgId'.
--
-- Format: @--instantiate-with=SigName=\<unit-id\>:ImplModuleName@
mkInstantiateWithOpts ::
[(ModuleName, PackageName, ModuleName)]
-- ^ Backpack instantiation entries: (sigName, implPkgName, implModuleName)
-> Map MungedPackageId GhcPkgId
-- ^ All dependency GhcPkgIds, keyed by munged identifier
-> [String]
mkInstantiateWithOpts entries depsMap =
[ "--instantiate-with="
++ C.display sigName
++ "="
++ ghcPkgIdString implGhcPkgId
++ ":"
++ C.display implModuleName
| (sigName, implPkgName, implModuleName) <- entries
, Just implGhcPkgId <- [findGhcPkgId depsMap implPkgName]
]
-- | Ensure that the configuration for the package matches what is given
ensureConfig ::
HasEnvConfig env
=> ConfigCache
-- ^ newConfigCache
-> Path Abs Dir
-- ^ package directory
-> BuildOpts
-> Maybe Text
-- ^ CInst hash suffix (Nothing for normal builds)
-> RIO env ()
-- ^ announce
-> (ExcludeTHLoading -> [String] -> RIO env ())
-- ^ cabal
-> Path Abs File
-- ^ Cabal file
-> Task
-> RIO env Bool
ensureConfig newConfigCache pkgDir buildOpts mInstSuffix announce cabal cabalFP task = do
-- CInst (Backpack instantiation) tasks share a source directory with the
-- indefinite package but use a separate --builddir. They use a separate
-- config cache entry (ConfigCacheTypeInstantiation) to avoid colliding with
-- the indefinite build's cache. File-based caches (cabalMod,
-- projectRoot) are shared since the .cabal file is the same, but
-- setup-config lives in the inst builddir and must be checked there.
let configCacheType =
maybe ConfigCacheTypeConfig ConfigCacheTypeInstantiation mInstSuffix
newCabalMod <-
liftIO $ modificationTime <$> getFileStatus (toFilePath cabalFP)
setupConfigfp <- case mInstSuffix of
Nothing -> setupConfigFromDir pkgDir
Just suffix -> do
dist <- distDirFromDir pkgDir
instSubDir <- parseRelDir ("inst-" ++ T.unpack suffix)
setupConfig <- parseRelFile "setup-config"
pure $ dist </> instSubDir </> setupConfig
let getNewSetupConfigMod =
liftIO $ either (const Nothing) (Just . modificationTime) <$>
tryJust
(guard . isDoesNotExistError)
(getFileStatus (toFilePath setupConfigfp))
newSetupConfigMod <- getNewSetupConfigMod
newConfigFileRoot <- S8.pack . toFilePath <$> view configFileRootL
needConfig <-
if buildOpts.reconfigure
-- The reason 'taskAnyMissing' is necessary is a bug in Cabal. See:
-- <https://github.com/haskell/cabal/issues/4728#issuecomment-337937673>.
-- The problem is that Cabal may end up generating the same package ID
-- for a dependency, even if the ABI has changed. As a result, without
-- check, Stack would think that a reconfigure is unnecessary, when in
-- fact we _do_ need to reconfigure. The details here suck. We really
-- need proper hashes for package identifiers.
then pure True
else do
-- We can ignore the components field of the Cabal configuration cache,
-- because it is only used to inform 'construct plan' that we need to
-- plan to build additional components. These components don't affect
-- the Cabal configuration for the package.
let ignoreComponents :: ConfigCache -> ConfigCache
ignoreComponents cc = cc { ConfigCache.components = Set.empty }
-- Determine the old and new Cabal configuration for the package
-- directory, to determine if we need to reconfigure.
mOldConfigCache <- tryGetConfigCache pkgDir configCacheType
mOldCabalMod <- tryGetCabalMod pkgDir
-- Cabal's setup-config is created per OS/Cabal version, multiple
-- projects using the same package could get a conflict because of this
mOldSetupConfigMod <- tryGetSetupConfigMod pkgDir
mOldProjectRoot <- tryGetPackageProjectRoot pkgDir
pure $
fmap ignoreComponents mOldConfigCache
/= Just (ignoreComponents newConfigCache)
|| mOldCabalMod /= Just newCabalMod
|| mOldSetupConfigMod /= newSetupConfigMod
|| mOldProjectRoot /= Just newConfigFileRoot
when task.buildTypeConfig $
-- When build-type is Configure, we need to have a configure script in the
-- local directory. If it doesn't exist, build it with autoreconf -i. See:
-- https://github.com/commercialhaskell/stack/issues/3534
ensureConfigureScript pkgDir
when needConfig $ do
deleteCaches pkgDir configCacheType
announce
cp <- view compilerPathsL
let (GhcPkgExe pkgPath) = cp.pkg
let programNames =
case cpWhich cp of
Ghc ->
[ ("ghc", toFilePath cp.compiler)
, ("ghc-pkg", toFilePath pkgPath)
]
exes <- forM programNames $ \(name, file) ->
findExecutable file <&> \case
Left _ -> []
Right x -> pure $ concat ["--with-", name, "=", x]
let allOpts =
concat exes
<> renderConfigureOpts newConfigCache.configureOpts
-- Configure cabal with arguments determined by
-- Stack.Types.Build.configureOpts
cabal KeepTHLoading $ "configure" : allOpts
-- Only write the cache for local packages. Remote packages are built in a
-- temporary directory so the cache would never be used anyway.
case task.taskType of
TTLocalMutable{} -> writeConfigCache pkgDir configCacheType newConfigCache
TTRemotePackage{} -> pure ()
-- File-based caches are shared with the indefinite build (same .cabal
-- file, same pkgDir). Only write them for normal (non-CInst) tasks to
-- avoid redundant writes.
when (isNothing mInstSuffix) $ do
writeCabalMod pkgDir newCabalMod
-- This file gets updated one more time by the configure step, so get the
-- most recent value. We could instead change our logic above to check if
-- our config mod file is newer than the file above, but this seems
-- reasonable too.
getNewSetupConfigMod >>= writeSetupConfigMod pkgDir
writePackageProjectRoot pkgDir newConfigFileRoot
pure needConfig
-- | Make a padded prefix for log messages
packageNamePrefix :: ExecuteEnv -> PackageName -> String
packageNamePrefix ee name' =
let name = packageNameString name'
paddedName =
case ee.largestPackageName of
Nothing -> name
Just len ->
assert (len >= length name) $ take len $ name ++ L.repeat ' '
in paddedName <> "> "
announceTask ::
HasLogFunc env
=> ExecuteEnv
-> TaskType
-> Utf8Builder
-> RIO env ()
announceTask ee taskType action = logInfo $
fromString
(packageNamePrefix ee (pkgName (taskTypePackageIdentifier taskType)))
<> action
-- | Implements running a package's build, used to implement
-- 'Control.Concurrent.Execute.ATBuild' tasks.
--
-- In particular this does the following:
--
-- * Checks if the package exists in the precompiled cache, and if so, add it to
-- the database instead of performing the build.
--
-- * Runs the configure step if needed (@ensureConfig@)
--
-- * Runs the build step
--
-- * Generates haddocks
--
-- * Registers the library and copies the built executables into the local
-- install directory. Note that this is literally invoking Cabal with @copy@,
-- and not the copying done by @stack install@ - that is handled by
-- 'Stack.Build.copyExecutables'.
singleBuild ::
forall env. (HasEnvConfig env, HasRunner env)
=> ActionContext
-> ExecuteEnv
-> Task
-> InstalledMap
-> Bool
-- ^ Is this a final build? (Controls enable-tests/--enable-benchmarks.)
-> Bool
-- ^ Is this a merged primary+final build? True only when a non-split
-- package's primary task is folded together with its final task in a
-- single Setup invocation, so lib/exe components are also built and
-- installed. Ignored when isFinalBuild is False.
-> ComponentKey
-- ^ The component key identifying which component this build is for.
-> RIO env ()
singleBuild
ac
ee
task
installedMap
isFinalBuild
isMergedBuild
ck
= do
(allDeps, cache) <-
getConfigCache ee task installedMap enableTests enableBenchmarks
let bcoSnapInstallRoot = ee.baseConfigOpts.snapInstallRoot
isCInstTask = case ck of
ComponentKey _ (CInst _) -> True
_ -> False
mprecompiled <- getPrecompiled isCInstTask cache task.taskType bcoSnapInstallRoot
minstalled <-
case mprecompiled of
Just precompiled ->
copyPreCompiled isCInstTask ee task pkgId precompiled
Nothing -> do
curator <- view $ buildConfigL . to (.curator)
realConfigAndBuild
ac
ee
task
installedMap
(enableTests, enableBenchmarks)
(isFinalBuild, buildingFinals, isMergedBuild)
cache
curator
allDeps
ck
-- For CInst (Backpack instantiation) tasks, do NOT update the ghcPkgIds
-- TVar. The consumer's --dependency flag must reference the indefinite
-- GhcPkgId (stored by the CLib task). Cabal resolves the instantiation
-- by looking up the package DB using mixin declarations. Writing the
-- flag cache is also skipped to avoid clobbering the indefinite build's
-- cache.
unless isCInstTask $
whenJust minstalled $ \installed -> do
writeFlagCache installed cache
liftIO $ atomically $ modifyTVar ee.ghcPkgIds $ Map.insert pkgId installed
where
pkgId = taskProvides task
buildingFinals = isFinalBuild
enableTests = buildingFinals
&& componentEnableTests ck (taskComponents task)
enableBenchmarks = buildingFinals
&& componentEnableBenchmarks ck (taskComponents task)
realConfigAndBuild ::
forall env a. HasEnvConfig env
=> ActionContext
-> ExecuteEnv
-> Task
-> Map PackageName (a, Installed)
-> (Bool, Bool)
-- ^ (enableTests, enableBenchmarks)
-> (Bool, Bool, Bool)
-- ^ (isFinalBuild, buildingFinals, isMergedBuild)
-> ConfigCache
-> Maybe Curator
-> Map MungedPackageId GhcPkgId
-- ^ Ids of installed packages that are assumed to be available to build a
-- package's custom @Setup.hs@, given its dependencies specified in its
-- @custom-setup@ stanza of its Cabal file.
-> ComponentKey
-> RIO env (Maybe Installed)
realConfigAndBuild
ac
ee
task
installedMap
(enableTests, enableBenchmarks)
(isFinalBuild, buildingFinals, isMergedBuild)
cache
mcurator0
allDepsMap
ck
= withSingleContext ac ee task.taskType allDepsMap Nothing mInstSuffix $
\package cabalFP pkgDir cabal0 announce _outputType -> do
let cabal = cabal0 CloseOnException
_neededConfig <-
ensureConfig
cache
pkgDir
ee.buildOpts
mInstSuffix
(announce ("configure" <> display annSuffix))
cabal
cabalFP
task
let installedMapHasThisPkg :: Bool
installedMapHasThisPkg =
case Map.lookup package.name installedMap of
Just (_, Library ident _) -> ident == pkgId
Just (_, Executable _) -> True
_ -> False
case ( ee.buildOptsCLI.onlyConfigure
, ee.buildOptsCLI.initialBuildSteps && taskIsTarget task
) of
-- A full build is done if there are downstream actions,
-- because their configure step will require that this
-- package is built. See
-- https://github.com/commercialhaskell/stack/issues/2787
(True, _) | null ac.downstream -> pure Nothing
(_, True) | null ac.downstream || installedMapHasThisPkg -> do
initialBuildSteps cabal announce
pure Nothing
_ -> fulfillCuratorBuildExpectations
pname
mcurator0
enableTests
enableBenchmarks
Nothing
(Just <$> realBuild package pkgDir cabal0 announce)
where
pkgId = taskProvides task
PackageIdentifier pname _ = pkgId
mInstSuffix = case ck of
ComponentKey _ (CInst hashSuffix) -> Just hashSuffix
_ -> Nothing
doHaddock curator =
task.buildHaddocks
-- Skip haddock only for pure finals-only builds (split CTest/CBench
-- or the non-split finalBuild action with no primary to go with).
-- Merged non-split builds still produce primary components, so run
-- haddock for them as we would for a plain primary build.
&& not (isFinalBuild && not isMergedBuild)
-- Special help for the curator tool to avoid haddocks that are known
-- to fail
&& maybe True (Set.notMember pname . (.skipHaddock)) curator
annSuffix = buildAnnSuffix ck task enableTests enableBenchmarks
initialBuildSteps cabal announce = do
announce ("initial-build-steps" <> display annSuffix)
cabal KeepTHLoading ["repl", "stack-initial-build-steps"]
realBuild ::
Package
-> Path Abs Dir
-> RunCabalWithArgs env
-- ^ Function to run Cabal (the library) with arguments.
-> (Utf8Builder -> RIO env ())
-- ^ A plain 'announce' function.
-> RIO env Installed
realBuild package pkgDir cabal0 announce = do
let cabal = cabal0 CloseOnException
wc <- view $ actualCompilerVersionL . whichCompilerL
markExeNotInstalled (taskLocation task) pkgId
case task.taskType of
TTLocalMutable lp -> do
when enableTests $ setTestStatus pkgDir TSUnknown
caches <- runMemoizedWith lp.newBuildCaches
mapM_
(uncurry (writeBuildCache pkgDir))
(Map.toList caches)
TTRemotePackage{} -> pure ()
-- FIXME: only output these if they're in the build plan.
let postBuildCheck _succeeded = do
mlocalWarnings <- case task.taskType of
TTLocalMutable lp -> do
warnings <- checkForUnlistedFiles task.taskType pkgDir
-- TODO: Perhaps only emit these warnings for non extra-dep?
pure (Just (lp.cabalFP, warnings))
_ -> pure Nothing
-- NOTE: once
-- https://github.com/commercialhaskell/stack/issues/2649
-- is resolved, we will want to partition the warnings
-- based on variety, and output in different lists.
let showModuleWarning (UnlistedModulesWarning comp modules) =
"- In" <+>
fromString (T.unpack (renderComponent comp)) <>
":" <> line <>
indent 4 ( mconcat
$ L.intersperse line
$ map
(style Good . fromString . C.display)
modules
)
forM_ mlocalWarnings $ \(cabalFP, warnings) ->
unless (null warnings) $ prettyWarn $
flow "The following modules should be added to \
\exposed-modules or other-modules in" <+>
pretty cabalFP
<> ":"
<> line
<> indent 4 ( mconcat
$ L.intersperse line
$ map showModuleWarning warnings
)
<> blankLine
<> flow "Missing modules in the Cabal file are likely to cause \
\undefined reference errors from the linker, along with \
\other problems."
actualCompiler <- view actualCompilerVersionL
() <- announce
( "build"
<> display annSuffix
<> " with "
<> display actualCompiler
)
config <- view configL
extraOpts <- extraBuildOptions wc ee.buildOpts ee.serverSemaphore
let stripTHLoading
| config.hideTHLoading = ExcludeTHLoading
| otherwise = KeepTHLoading
let (buildOpts, copyOpts) =
buildAndCopyOpts task.taskType ck isFinalBuild isMergedBuild
cabal stripTHLoading ("build" : buildOpts <> extraOpts)
`catch` \ex -> case ex of
CabalExitedUnsuccessfully{} ->
postBuildCheck False >> prettyThrowM ex
_ -> throwM ex
postBuildCheck True
mcurator <- view $ buildConfigL . to (.curator)
when (doHaddock mcurator) $ do
let isTaskTargetMutable = taskTargetIsMutable task == Mutable
isHaddockForHackage =
ee.buildOpts.haddockForHackage && isTaskTargetMutable
announce $ if isHaddockForHackage
then "haddock for Hackage"
else "haddock"
-- For GHC 8.4 and later, provide the --quickjump option.
let quickjump = ["--haddock-option=--quickjump"]
fulfillHaddockExpectations pname mcurator $ \keep -> do
let args = concat
( ( if isHaddockForHackage
then
[ [ "--for-hackage" ] ]
else
[ [ "--html"
, "--hoogle"
, "--html-location=../$pkg-$version/"
]
, [ "--haddock-option=--hyperlinked-source"
| ee.buildOpts.haddockHyperlinkSource
]
, [ "--executables" | ee.buildOpts.haddockExecutables ]
, [ "--tests" | ee.buildOpts.haddockTests ]
, [ "--benchmarks" | ee.buildOpts.haddockBenchmarks ]
, [ "--internal" | ee.buildOpts.haddockInternal ]
, quickjump
]
)
<> [ [ "--haddock-option=" <> opt
| opt <- ee.buildOpts.haddockOpts.additionalArgs
]
]
)
cabal0 keep KeepTHLoading $ "haddock" : args
let hasLibrary = hasBuildableMainLibrary package
hasSubLibraries = not $ null package.subLibraries
hasExecutables = not $ null package.executables
-- Skip copy/install only for pure finals-only builds: split
-- CTest/CBench components and non-split finalBuild actions that
-- follow a clean primary. Every other path — plain primary
-- builds, split primary components, merged primary+final non-split
-- builds, and intra-package Backpack CLib/CInst builds — copies
-- and registers as before.
shouldCopy =
not (isFinalBuild && not isMergedBuild)
&& (hasLibrary || hasSubLibraries || hasExecutables)
when shouldCopy $ withMVar ee.installLock $ \() -> do
announce "copy/register"
try (cabal KeepTHLoading $ "copy" : copyOpts) >>= \case
Left err@CabalExitedUnsuccessfully{} ->
prettyThrowM $ CabalCopyFailed
(package.buildType == C.Simple)
err
_ -> pure ()
when (hasLibrary || hasSubLibraries) $ cabal KeepTHLoading ["register"]
copyDdumpFilesIfNeeded buildingFinals ee.buildOpts.ddumpDir
installedPkg <-
fetchAndMarkInstalledPackage ee (taskLocation task) package pkgId
postProcessRemotePackage
task.taskType
ac
cache
ee
installedPkg
package
pkgId
pkgDir
pure installedPkg
-- | Action in the case that the task relates to a remote package.
postProcessRemotePackage ::
(HasEnvConfig env)
=> TaskType
-> ActionContext
-> ConfigCache
-> ExecuteEnv
-> Installed
-> Package
-> PackageIdentifier
-> Path b Dir
-> RIO env ()
postProcessRemotePackage
taskType
ac
cache
ee
installedPackage
package
pkgId
pkgDir
= case taskType of
TTRemotePackage isMutable _ loc -> do
when (isMutable == Immutable) $ writePrecompiledCache
ee.baseConfigOpts
loc
cache.configureOpts
cache.buildHaddocks
installedPackage
(buildableExes package)
-- For packages from a package index, pkgDir is in the tmp directory. We
-- eagerly delete it if no other tasks require it, to reduce space usage
-- in tmp (#3018).
let remaining =
Set.filter
(\(ActionId ck _) -> componentKeyPkgName ck == pkgName pkgId)
ac.remaining
when (null remaining) $ removeDirRecur pkgDir
_ -> pure ()
-- | Once all the Cabal-related tasks have run for a package, we should be able
-- to gather the information needed to create an 'Installed' package value. For
-- now, either there's a main library (in which case we consider the 'GhcPkgId'
-- values of the package's libraries) or we just consider it's an executable
-- (and mark all the executables as installed, if any).
--
-- Note that this also modifies the installedDumpPkgsTVar which is used for
-- generating Haddocks.
--
fetchAndMarkInstalledPackage ::
(HasEnvConfig env, HasTerm env)
=> ExecuteEnv
-> InstallLocation
-> Package
-> PackageIdentifier
-> RIO env Installed
fetchAndMarkInstalledPackage ee taskInstallLocation package pkgId = do
let hasMainLibrary = hasBuildableMainLibrary package
subLibs = package.subLibraries
if not hasMainLibrary && null subLibs
then do
markExeInstalled taskInstallLocation pkgId
-- TODO: Unify the above somehow with writeFlagCache?
pure $ Executable pkgId
else do
ghcPkgId <- if hasMainLibrary
then ghcPkgIdLoader Nothing
else pure Nothing
subLibsPkgIds <-
foldComponentToAnotherCollection subLibs foldSubLibToMap mempty
pure $ simpleInstalledLib pkgId ghcPkgId subLibsPkgIds
where
ghcPkgIdLoader = fetchGhcPkgIdForLib ee taskInstallLocation package.name
foldSubLibToMap subLib mapInMonad = do
maybeGhcpkgId <- ghcPkgIdLoader (Just subLib.name)
mapInMonad <&> case maybeGhcpkgId of
Just v -> Map.insert subLib.name v
_ -> id
fetchGhcPkgIdForLib ::
(HasTerm env, HasEnvConfig env)
=> ExecuteEnv
-> InstallLocation
-> PackageName
-> Maybe Component.StackUnqualCompName
-> RIO env (Maybe GhcPkgId)
fetchGhcPkgIdForLib ee installLocation pkgName mLibName = do
let baseConfigOpts = ee.baseConfigOpts
(installedPkgDb, installedDumpPkgsTVar) =
case installLocation of
Snap ->
( baseConfigOpts.snapDB
, ee.snapshotDumpPkgs )
Local ->
( baseConfigOpts.localDB
, ee.localDumpPkgs )
let commonLoader = loadInstalledPkg [installedPkgDb] installedDumpPkgsTVar
mungedPkgName = toCabalMungedPackageName pkgName mLibName
encodedPkgName = encodeCompatPackageName mungedPkgName
commonLoader encodedPkgName
-- | Copy ddump-* files, if we are building finals and a non-empty ddump-dir
-- has been specified.
copyDdumpFilesIfNeeded :: HasEnvConfig env => Bool -> Maybe Text -> RIO env ()
copyDdumpFilesIfNeeded buildingFinals mDdumpPath = when buildingFinals $
whenJust mDdumpPath $ \ddumpPath -> unless (T.null ddumpPath) $ do
distDir <- distRelativeDir
ddumpRelDir <- parseRelDir $ T.unpack ddumpPath
prettyDebugL
[ "ddump-dir:"
, pretty ddumpRelDir
]
prettyDebugL
[ "dist-dir:"
, pretty distDir
]
runConduitRes
$ CF.sourceDirectoryDeep False (toFilePath distDir)
.| CL.filter (L.isInfixOf ".dump-")
.| CL.mapM_ (\src -> liftIO $ do
parentDir <- parent <$> parseRelDir src
destBaseDir <-
(ddumpRelDir </>) <$> stripProperPrefix distDir parentDir
-- exclude .stack-work dir
unless (".stack-work" `L.isInfixOf` toFilePath destBaseDir) $ do
ensureDir destBaseDir
src' <- parseRelFile src
copyFile src' (destBaseDir </> filename src'))
getPrecompiled ::
HasEnvConfig env
=> Bool
-- ^ Is this a CInst (Backpack instantiation) task? CInst tasks are
-- always created by addInstantiationTasks even when the instantiated
-- package is already registered. Skip the self-reference check so
-- the precompiled cache can short-circuit the build.
-> ConfigCache
-> TaskType
-> Path Abs Dir
-> RIO env (Maybe (PrecompiledCache Abs))
getPrecompiled isCInst cache taskType bcoSnapInstallRoot =
case taskType of
TTRemotePackage Immutable _ loc ->
readPrecompiledCache loc cache.configureOpts cache.buildHaddocks >>= \case
Nothing -> pure Nothing
-- Only pay attention to precompiled caches that refer to packages
-- within the snapshot. For CInst tasks, skip this check: CInst
-- tasks are always created regardless of whether the instantiated
-- package is already installed, and re-registering with --force is
-- harmless.
Just pc
| not isCInst
, maybe False
(bcoSnapInstallRoot `isProperPrefixOf`)
pc.library -> pure Nothing
-- If old precompiled cache files are left around but snapshots are
-- deleted, it is possible for the precompiled file to refer to the
-- very library we're building, and if flags are changed it may try to
-- copy the library to itself. This check prevents that from
-- happening.
Just pc -> do
let allM _ [] = pure True
allM f (x:xs) = do
b <- f x
if b then allM f xs else pure False
b <- liftIO $
allM doesFileExist $ maybe id (:) pc.library pc.exes
pure $ if b then Just pc else Nothing
_ -> pure Nothing
copyPreCompiled ::
( HasLogFunc env
, HasCompiler env
, HasTerm env
, HasProcessContext env
, HasEnvConfig env
)
=> Bool
-- ^ Is this a CInst (Backpack instantiation) task? If so, skip
-- unregistration — the indefinite package and other instantiations
-- must remain in the DB.
-> ExecuteEnv
-> Task
-> PackageIdentifier
-> PrecompiledCache b0
-> RIO env (Maybe Installed)
copyPreCompiled isCInst ee task pkgId (PrecompiledCache mlib subLibs exes) = do
let PackageIdentifier pname pversion = pkgId
announceTask ee task.taskType "using precompiled package"
-- We need to copy .conf files for the main library and all sub-libraries
-- which exist in the cache, from their old snapshot to the new one.
-- However, we must unregister any such library in the new snapshot, in case
-- it was built with different flags. For CInst tasks, we skip unregistration
-- because the indefinite package and other instantiations share the same
-- package name and must remain in the DB. The --force flag on register
-- handles any conflicts.
let
subLibNames = Set.toList $ buildableSubLibs $ case task.taskType of
TTLocalMutable lp -> lp.package
TTRemotePackage _ p _ -> p
toMungedPackageId :: StackUnqualCompName -> MungedPackageId
toMungedPackageId subLib =
let subLibName = LSubLibName $ toCabalName subLib
in MungedPackageId (MungedPackageName pname subLibName) pversion
toPackageId :: MungedPackageId -> PackageIdentifier
toPackageId (MungedPackageId n v) =
PackageIdentifier (encodeCompatPackageName n) v
allToUnregister :: [Either PackageIdentifier GhcPkgId]
allToUnregister = mcons
(Left pkgId <$ mlib)
(map (Left . toPackageId . toMungedPackageId) subLibNames)
allToRegister = mcons mlib subLibs
unless (null allToRegister) $
withMVar ee.installLock $ \() -> do
-- We want to ignore the global and user package databases. ghc-pkg
-- allows us to specify --no-user-package-db and --package-db=<db> on
-- the command line.
let pkgDb = ee.baseConfigOpts.snapDB
ghcPkgExe <- getGhcPkgExe
-- First unregister, silently, everything that needs to be unregistered.
-- Skip for CInst tasks to preserve the indefinite and other instantiated
-- entries.
unless isCInst $
whenJust (nonEmpty allToUnregister) $ \allToUnregister' -> do
logLevel <- view $ globalOptsL . to (.logLevel)
let isDebug = logLevel == LevelDebug
catchAny
(unregisterGhcPkgIds isDebug ghcPkgExe pkgDb allToUnregister')
(const (pure ()))
-- There appears to be a bug in the ghc-pkg executable such that, on
-- Windows only, it cannot register a package into a package database that
-- is also listed in the GHC_PACKAGE_PATH environment variable. See:
-- https://gitlab.haskell.org/ghc/ghc/-/issues/25962. We work around that
-- by removing GHC_PACKAGE_PATH from the environment for the register