forked from commercialhaskell/stack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPackage.hs
More file actions
1395 lines (1317 loc) · 56.6 KB
/
Package.hs
File metadata and controls
1395 lines (1317 loc) · 56.6 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 TupleSections #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
-- | Dealing with Cabal.
module Stack.Package
(readDotBuildinfo
,resolvePackage
,packageFromPackageDescription
,Package(..)
,PackageDescriptionPair(..)
,GetPackageFiles(..)
,GetPackageOpts(..)
,PackageConfig(..)
,buildLogPath
,PackageException (..)
,resolvePackageDescription
,packageDependencies
,applyForceCustomBuild
) where
import Data.List (find, isPrefixOf, unzip)
import Data.Maybe (maybe)
import qualified Data.Map.Strict as M
import qualified Data.Set as S
import qualified Data.Text as T
import Distribution.Compiler
import Distribution.ModuleName (ModuleName)
import qualified Distribution.ModuleName as Cabal
import qualified Distribution.Package as D
import Distribution.Package hiding (Package,PackageName,packageName,packageVersion,PackageIdentifier)
import qualified Distribution.PackageDescription as D
import Distribution.PackageDescription hiding (FlagName)
import Distribution.PackageDescription.Parsec
import Distribution.Simple.Glob (matchDirFileGlob)
import Distribution.System (OS (..), Arch, Platform (..))
import qualified Distribution.Text as D
import qualified Distribution.Types.CondTree as Cabal
import qualified Distribution.Types.ExeDependency as Cabal
import Distribution.Types.ForeignLib
import qualified Distribution.Types.LegacyExeDependency as Cabal
import Distribution.Types.MungedPackageName
import qualified Distribution.Types.UnqualComponentName as Cabal
import qualified Distribution.Verbosity as D
import Distribution.Version (mkVersion, orLaterVersion, anyVersion)
import qualified HiFileParser as Iface
import Path as FL
import Path.Extra
import Path.IO hiding (findFiles)
import Stack.Build.Installed
import Stack.Constants
import Stack.Constants.Config
import Stack.Prelude hiding (Display (..))
import Stack.Types.Compiler
import Stack.Types.Config
import Stack.Types.GhcPkgId
import Stack.Types.NamedComponent
import Stack.Types.Package
import Stack.Types.Version
import qualified System.Directory as D
import System.FilePath (replaceExtension)
import qualified System.FilePath as FilePath
import System.IO.Error
import RIO.Process
import RIO.PrettyPrint
import qualified RIO.PrettyPrint as PP (Style (Module))
data Ctx = Ctx { ctxFile :: !(Path Abs File)
, ctxDistDir :: !(Path Abs Dir)
, ctxBuildConfig :: !BuildConfig
}
instance HasPlatform Ctx
instance HasGHCVariant Ctx
instance HasLogFunc Ctx where
logFuncL = configL.logFuncL
instance HasRunner Ctx where
runnerL = configL.runnerL
instance HasStylesUpdate Ctx where
stylesUpdateL = runnerL.stylesUpdateL
instance HasTerm Ctx where
useColorL = runnerL.useColorL
termWidthL = runnerL.termWidthL
instance HasConfig Ctx
instance HasPantryConfig Ctx where
pantryConfigL = configL.pantryConfigL
instance HasProcessContext Ctx where
processContextL = configL.processContextL
instance HasBuildConfig Ctx where
buildConfigL = lens ctxBuildConfig (\x y -> x { ctxBuildConfig = y })
-- | Read @<package>.buildinfo@ ancillary files produced by some Setup.hs hooks.
-- The file includes Cabal file syntax to be merged into the package description
-- derived from the package's .cabal file.
--
-- NOTE: not to be confused with BuildInfo, an Stack-internal datatype.
readDotBuildinfo :: MonadIO m
=> Path Abs File
-> m HookedBuildInfo
readDotBuildinfo buildinfofp =
liftIO $ readHookedBuildInfo D.silent (toFilePath buildinfofp)
-- | Resolve a parsed cabal file into a 'Package', which contains all of
-- the info needed for stack to build the 'Package' given the current
-- configuration.
resolvePackage :: PackageConfig
-> GenericPackageDescription
-> Package
resolvePackage packageConfig gpkg =
packageFromPackageDescription
packageConfig
(genPackageFlags gpkg)
(resolvePackageDescription packageConfig gpkg)
packageFromPackageDescription :: PackageConfig
-> [D.Flag]
-> PackageDescriptionPair
-> Package
packageFromPackageDescription packageConfig pkgFlags (PackageDescriptionPair pkgNoMod pkg) =
Package
{ packageName = name
, packageVersion = pkgVersion pkgId
, packageLicense = licenseRaw pkg
, packageDeps = deps
, packageFiles = pkgFiles
, packageUnknownTools = unknownTools
, packageGhcOptions = packageConfigGhcOptions packageConfig
, packageCabalConfigOpts = packageConfigCabalConfigOpts packageConfig
, packageFlags = packageConfigFlags packageConfig
, packageDefaultFlags = M.fromList
[(flagName flag, flagDefault flag) | flag <- pkgFlags]
, packageAllDeps = S.fromList (M.keys deps)
, packageLibraries =
let mlib = do
lib <- library pkg
guard $ buildable $ libBuildInfo lib
Just lib
in
case mlib of
Nothing -> NoLibraries
Just _ -> HasLibraries foreignLibNames
, packageInternalLibraries = subLibNames
, packageTests = M.fromList
[(T.pack (Cabal.unUnqualComponentName $ testName t), testInterface t)
| t <- testSuites pkgNoMod
, buildable (testBuildInfo t)
]
, packageBenchmarks = S.fromList
[T.pack (Cabal.unUnqualComponentName $ benchmarkName b)
| b <- benchmarks pkgNoMod
, buildable (benchmarkBuildInfo b)
]
-- Same comment about buildable applies here too.
, packageExes = S.fromList
[T.pack (Cabal.unUnqualComponentName $ exeName biBuildInfo)
| biBuildInfo <- executables pkg
, buildable (buildInfo biBuildInfo)]
-- This is an action used to collect info needed for "stack ghci".
-- This info isn't usually needed, so computation of it is deferred.
, packageOpts = GetPackageOpts $
\installMap installedMap omitPkgs addPkgs cabalfp ->
do (componentsModules,componentFiles,_,_) <- getPackageFiles pkgFiles cabalfp
let internals = S.toList $ internalLibComponents $ M.keysSet componentsModules
excludedInternals <- mapM (parsePackageNameThrowing . T.unpack) internals
mungedInternals <- mapM (parsePackageNameThrowing . T.unpack .
toInternalPackageMungedName) internals
componentsOpts <-
generatePkgDescOpts installMap installedMap
(excludedInternals ++ omitPkgs) (mungedInternals ++ addPkgs)
cabalfp pkg componentFiles
return (componentsModules,componentFiles,componentsOpts)
, packageHasExposedModules = maybe
False
(not . null . exposedModules)
(library pkg)
, packageBuildType = buildType pkg
, packageSetupDeps = msetupDeps
, packageCabalSpec = either orLaterVersion id $ specVersionRaw pkg
}
where
extraLibNames = S.union subLibNames foreignLibNames
subLibNames
= S.fromList
$ map (T.pack . Cabal.unUnqualComponentName)
$ mapMaybe libName -- this is a design bug in the Cabal API: this should statically be known to exist
$ filter (buildable . libBuildInfo)
$ subLibraries pkg
foreignLibNames
= S.fromList
$ map (T.pack . Cabal.unUnqualComponentName . foreignLibName)
$ filter (buildable . foreignLibBuildInfo)
$ foreignLibs pkg
toInternalPackageMungedName
= T.pack . unMungedPackageName . computeCompatPackageName (pkgName pkgId)
. Just . Cabal.mkUnqualComponentName . T.unpack
-- Gets all of the modules, files, build files, and data files that
-- constitute the package. This is primarily used for dirtiness
-- checking during build, as well as use by "stack ghci"
pkgFiles = GetPackageFiles $
\cabalfp -> debugBracket ("getPackageFiles" <+> pretty cabalfp) $ do
let pkgDir = parent cabalfp
distDir <- distDirFromDir pkgDir
bc <- view buildConfigL
(componentModules,componentFiles,dataFiles',warnings) <-
runRIO
(Ctx cabalfp distDir bc)
(packageDescModulesAndFiles pkg)
setupFiles <-
if buildType pkg == Custom
then do
let setupHsPath = pkgDir </> relFileSetupHs
setupLhsPath = pkgDir </> relFileSetupLhs
setupHsExists <- doesFileExist setupHsPath
if setupHsExists then return (S.singleton setupHsPath) else do
setupLhsExists <- doesFileExist setupLhsPath
if setupLhsExists then return (S.singleton setupLhsPath) else return S.empty
else return S.empty
buildFiles <- liftM (S.insert cabalfp . S.union setupFiles) $ do
let hpackPath = pkgDir </> relFileHpackPackageConfig
hpackExists <- doesFileExist hpackPath
return $ if hpackExists then S.singleton hpackPath else S.empty
return (componentModules, componentFiles, buildFiles <> dataFiles', warnings)
pkgId = package pkg
name = pkgName pkgId
(unknownTools, knownTools) = packageDescTools pkg
deps = M.filterWithKey (const . not . isMe) (M.unionsWith (<>)
[ asLibrary <$> packageDependencies packageConfig pkg
-- We include all custom-setup deps - if present - in the
-- package deps themselves. Stack always works with the
-- invariant that there will be a single installed package
-- relating to a package name, and this applies at the setup
-- dependency level as well.
, asLibrary <$> fromMaybe M.empty msetupDeps
, knownTools
])
msetupDeps = fmap
(M.fromList . map (depName &&& depRange) . setupDepends)
(setupBuildInfo pkg)
asLibrary range = DepValue
{ dvVersionRange = range
, dvType = AsLibrary
}
-- Is the package dependency mentioned here me: either the package
-- name itself, or the name of one of the sub libraries
isMe name' = name' == name || fromString (packageNameString name') `S.member` extraLibNames
-- | Generate GHC options for the package's components, and a list of
-- options which apply generally to the package, not one specific
-- component.
generatePkgDescOpts
:: (HasEnvConfig env, MonadThrow m, MonadReader env m, MonadIO m)
=> InstallMap
-> InstalledMap
-> [PackageName] -- ^ Packages to omit from the "-package" / "-package-id" flags
-> [PackageName] -- ^ Packages to add to the "-package" flags
-> Path Abs File
-> PackageDescription
-> Map NamedComponent [DotCabalPath]
-> m (Map NamedComponent BuildInfoOpts)
generatePkgDescOpts installMap installedMap omitPkgs addPkgs cabalfp pkg componentPaths = do
config <- view configL
cabalVer <- view cabalVersionL
distDir <- distDirFromDir cabalDir
let generate namedComponent binfo =
( namedComponent
, generateBuildInfoOpts BioInput
{ biInstallMap = installMap
, biInstalledMap = installedMap
, biCabalDir = cabalDir
, biDistDir = distDir
, biOmitPackages = omitPkgs
, biAddPackages = addPkgs
, biBuildInfo = binfo
, biDotCabalPaths = fromMaybe [] (M.lookup namedComponent componentPaths)
, biConfigLibDirs = configExtraLibDirs config
, biConfigIncludeDirs = configExtraIncludeDirs config
, biComponentName = namedComponent
, biCabalVersion = cabalVer
}
)
return
( M.fromList
(concat
[ maybe
[]
(return . generate CLib . libBuildInfo)
(library pkg)
, mapMaybe
(\sublib -> do
let maybeLib = CInternalLib . T.pack . Cabal.unUnqualComponentName <$> libName sublib
flip generate (libBuildInfo sublib) <$> maybeLib
)
(subLibraries pkg)
, fmap
(\exe ->
generate
(CExe (T.pack (Cabal.unUnqualComponentName (exeName exe))))
(buildInfo exe))
(executables pkg)
, fmap
(\bench ->
generate
(CBench (T.pack (Cabal.unUnqualComponentName (benchmarkName bench))))
(benchmarkBuildInfo bench))
(benchmarks pkg)
, fmap
(\test ->
generate
(CTest (T.pack (Cabal.unUnqualComponentName (testName test))))
(testBuildInfo test))
(testSuites pkg)]))
where
cabalDir = parent cabalfp
-- | Input to 'generateBuildInfoOpts'
data BioInput = BioInput
{ biInstallMap :: !InstallMap
, biInstalledMap :: !InstalledMap
, biCabalDir :: !(Path Abs Dir)
, biDistDir :: !(Path Abs Dir)
, biOmitPackages :: ![PackageName]
, biAddPackages :: ![PackageName]
, biBuildInfo :: !BuildInfo
, biDotCabalPaths :: ![DotCabalPath]
, biConfigLibDirs :: ![FilePath]
, biConfigIncludeDirs :: ![FilePath]
, biComponentName :: !NamedComponent
, biCabalVersion :: !Version
}
-- | Generate GHC options for the target. Since Cabal also figures out
-- these options, currently this is only used for invoking GHCI (via
-- stack ghci).
generateBuildInfoOpts :: BioInput -> BuildInfoOpts
generateBuildInfoOpts BioInput {..} =
BuildInfoOpts
{ bioOpts = ghcOpts ++ cppOptions biBuildInfo
-- NOTE for future changes: Due to this use of nubOrd (and other uses
-- downstream), these generated options must not rely on multiple
-- argument sequences. For example, ["--main-is", "Foo.hs", "--main-
-- is", "Bar.hs"] would potentially break due to the duplicate
-- "--main-is" being removed.
--
-- See https://github.com/commercialhaskell/stack/issues/1255
, bioOneWordOpts = nubOrd $ concat
[extOpts, srcOpts, includeOpts, libOpts, fworks, cObjectFiles]
, bioPackageFlags = deps
, bioCabalMacros = componentAutogen </> relFileCabalMacrosH
}
where
cObjectFiles =
mapMaybe (fmap toFilePath .
makeObjectFilePathFromC biCabalDir biComponentName biDistDir)
cfiles
cfiles = mapMaybe dotCabalCFilePath biDotCabalPaths
installVersion = snd
-- Generates: -package=base -package=base16-bytestring-0.1.1.6 ...
deps =
concat
[ case M.lookup name biInstalledMap of
Just (_, Stack.Types.Package.Library _ident ipid _) -> ["-package-id=" <> ghcPkgIdString ipid]
_ -> ["-package=" <> packageNameString name <>
maybe "" -- This empty case applies to e.g. base.
((("-" <>) . versionString) . installVersion)
(M.lookup name biInstallMap)]
| name <- pkgs]
pkgs =
biAddPackages ++
[ name
| Dependency name _ <- targetBuildDepends biBuildInfo
, name `notElem` biOmitPackages]
ghcOpts = concatMap snd . filter (isGhc . fst) $ options biBuildInfo
where
isGhc GHC = True
isGhc _ = False
extOpts = map (("-X" ++) . D.display) (usedExtensions biBuildInfo)
srcOpts =
map (("-i" <>) . toFilePathNoTrailingSep)
(concat
[ [ componentBuildDir biCabalVersion biComponentName biDistDir ]
, [ biCabalDir
| null (hsSourceDirs biBuildInfo)
]
, mapMaybe toIncludeDir (hsSourceDirs biBuildInfo)
, [ componentAutogen ]
, maybeToList (packageAutogenDir biCabalVersion biDistDir)
, [ componentOutputDir biComponentName biDistDir ]
]) ++
[ "-stubdir=" ++ toFilePathNoTrailingSep (buildDir biDistDir) ]
componentAutogen = componentAutogenDir biCabalVersion biComponentName biDistDir
toIncludeDir "." = Just biCabalDir
toIncludeDir relDir = concatAndColapseAbsDir biCabalDir relDir
includeOpts =
map ("-I" <>) (biConfigIncludeDirs <> pkgIncludeOpts)
pkgIncludeOpts =
[ toFilePathNoTrailingSep absDir
| dir <- includeDirs biBuildInfo
, absDir <- handleDir dir
]
libOpts =
map ("-l" <>) (extraLibs biBuildInfo) <>
map ("-L" <>) (biConfigLibDirs <> pkgLibDirs)
pkgLibDirs =
[ toFilePathNoTrailingSep absDir
| dir <- extraLibDirs biBuildInfo
, absDir <- handleDir dir
]
handleDir dir = case (parseAbsDir dir, parseRelDir dir) of
(Just ab, _ ) -> [ab]
(_ , Just rel) -> [biCabalDir </> rel]
(Nothing, Nothing ) -> []
fworks = map (\fwk -> "-framework=" <> fwk) (frameworks biBuildInfo)
-- | Make the .o path from the .c file path for a component. Example:
--
-- @
-- executable FOO
-- c-sources: cbits/text_search.c
-- @
--
-- Produces
--
-- <dist-dir>/build/FOO/FOO-tmp/cbits/text_search.o
--
-- Example:
--
-- λ> makeObjectFilePathFromC
-- $(mkAbsDir "/Users/chris/Repos/hoogle")
-- CLib
-- $(mkAbsDir "/Users/chris/Repos/hoogle/.stack-work/Cabal-x.x.x/dist")
-- $(mkAbsFile "/Users/chris/Repos/hoogle/cbits/text_search.c")
-- Just "/Users/chris/Repos/hoogle/.stack-work/Cabal-x.x.x/dist/build/cbits/text_search.o"
-- λ> makeObjectFilePathFromC
-- $(mkAbsDir "/Users/chris/Repos/hoogle")
-- (CExe "hoogle")
-- $(mkAbsDir "/Users/chris/Repos/hoogle/.stack-work/Cabal-x.x.x/dist")
-- $(mkAbsFile "/Users/chris/Repos/hoogle/cbits/text_search.c")
-- Just "/Users/chris/Repos/hoogle/.stack-work/Cabal-x.x.x/dist/build/hoogle/hoogle-tmp/cbits/text_search.o"
-- λ>
makeObjectFilePathFromC
:: MonadThrow m
=> Path Abs Dir -- ^ The cabal directory.
-> NamedComponent -- ^ The name of the component.
-> Path Abs Dir -- ^ Dist directory.
-> Path Abs File -- ^ The path to the .c file.
-> m (Path Abs File) -- ^ The path to the .o file for the component.
makeObjectFilePathFromC cabalDir namedComponent distDir cFilePath = do
relCFilePath <- stripProperPrefix cabalDir cFilePath
relOFilePath <-
parseRelFile (replaceExtension (toFilePath relCFilePath) "o")
return (componentOutputDir namedComponent distDir </> relOFilePath)
-- | Make the global autogen dir if Cabal version is new enough.
packageAutogenDir :: Version -> Path Abs Dir -> Maybe (Path Abs Dir)
packageAutogenDir cabalVer distDir
| cabalVer < mkVersion [2, 0] = Nothing
| otherwise = Just $ buildDir distDir </> relDirGlobalAutogen
-- | Make the autogen dir.
componentAutogenDir :: Version -> NamedComponent -> Path Abs Dir -> Path Abs Dir
componentAutogenDir cabalVer component distDir =
componentBuildDir cabalVer component distDir </> relDirAutogen
-- | See 'Distribution.Simple.LocalBuildInfo.componentBuildDir'
componentBuildDir :: Version -> NamedComponent -> Path Abs Dir -> Path Abs Dir
componentBuildDir cabalVer component distDir
| cabalVer < mkVersion [2, 0] = buildDir distDir
| otherwise =
case component of
CLib -> buildDir distDir
CInternalLib name -> buildDir distDir </> componentNameToDir name
CExe name -> buildDir distDir </> componentNameToDir name
CTest name -> buildDir distDir </> componentNameToDir name
CBench name -> buildDir distDir </> componentNameToDir name
-- | The directory where generated files are put like .o or .hs (from .x files).
componentOutputDir :: NamedComponent -> Path Abs Dir -> Path Abs Dir
componentOutputDir namedComponent distDir =
case namedComponent of
CLib -> buildDir distDir
CInternalLib name -> makeTmp name
CExe name -> makeTmp name
CTest name -> makeTmp name
CBench name -> makeTmp name
where
makeTmp name =
buildDir distDir </> componentNameToDir (name <> "/" <> name <> "-tmp")
-- | Make the build dir. Note that Cabal >= 2.0 uses the
-- 'componentBuildDir' above for some things.
buildDir :: Path Abs Dir -> Path Abs Dir
buildDir distDir = distDir </> relDirBuild
-- NOTE: don't export this, only use it for valid paths based on
-- component names.
componentNameToDir :: Text -> Path Rel Dir
componentNameToDir name =
fromMaybe (error "Invariant violated: component names should always parse as directory names")
(parseRelDir (T.unpack name))
-- | Get all dependencies of the package (buildable targets only).
--
-- Note that for Cabal versions 1.22 and earlier, there is a bug where
-- Cabal requires dependencies for non-buildable components to be
-- present. We're going to use GHC version as a proxy for Cabal
-- library version in this case for simplicity, so we'll check for GHC
-- being 7.10 or earlier. This obviously makes our function a lot more
-- fun to write...
packageDependencies
:: PackageConfig
-> PackageDescription
-> Map PackageName VersionRange
packageDependencies pkgConfig pkg' =
M.fromListWith intersectVersionRanges $
map (depName &&& depRange) $
concatMap targetBuildDepends (allBuildInfo' pkg) ++
maybe [] setupDepends (setupBuildInfo pkg)
where
pkg
| getGhcVersion (packageConfigCompilerVersion pkgConfig) >= mkVersion [8, 0] = pkg'
-- Set all components to buildable. Only need to worry about
-- library, exe, test, and bench, since others didn't exist in
-- older Cabal versions
| otherwise = pkg'
{ library = (\c -> c { libBuildInfo = go (libBuildInfo c) }) <$> library pkg'
, executables = (\c -> c { buildInfo = go (buildInfo c) }) <$> executables pkg'
, testSuites =
if packageConfigEnableTests pkgConfig
then (\c -> c { testBuildInfo = go (testBuildInfo c) }) <$> testSuites pkg'
else testSuites pkg'
, benchmarks =
if packageConfigEnableBenchmarks pkgConfig
then (\c -> c { benchmarkBuildInfo = go (benchmarkBuildInfo c) }) <$> benchmarks pkg'
else benchmarks pkg'
}
go bi = bi { buildable = True }
-- | Get all dependencies of the package (buildable targets only).
--
-- This uses both the new 'buildToolDepends' and old 'buildTools'
-- information.
packageDescTools
:: PackageDescription
-> (Set ExeName, Map PackageName DepValue)
packageDescTools pd =
(S.fromList $ concat unknowns, M.fromListWith (<>) $ concat knowns)
where
(unknowns, knowns) = unzip $ map perBI $ allBuildInfo' pd
perBI :: BuildInfo -> ([ExeName], [(PackageName, DepValue)])
perBI bi =
(unknownTools, tools)
where
(unknownTools, knownTools) = partitionEithers $ map go1 (buildTools bi)
tools = mapMaybe go2 (knownTools ++ buildToolDepends bi)
-- This is similar to desugarBuildTool from Cabal, however it
-- uses our own hard-coded map which drops tools shipped with
-- GHC (like hsc2hs), and includes some tools from Stackage.
go1 :: Cabal.LegacyExeDependency -> Either ExeName Cabal.ExeDependency
go1 (Cabal.LegacyExeDependency name range) =
case M.lookup name hardCodedMap of
Just pkgName -> Right $ Cabal.ExeDependency pkgName (Cabal.mkUnqualComponentName name) range
Nothing -> Left $ ExeName $ T.pack name
go2 :: Cabal.ExeDependency -> Maybe (PackageName, DepValue)
go2 (Cabal.ExeDependency pkg _name range)
| pkg `S.member` preInstalledPackages = Nothing
| otherwise = Just
( pkg
, DepValue
{ dvVersionRange = range
, dvType = AsBuildTool
}
)
-- | A hard-coded map for tool dependencies
hardCodedMap :: Map String D.PackageName
hardCodedMap = M.fromList
[ ("alex", Distribution.Package.mkPackageName "alex")
, ("happy", Distribution.Package.mkPackageName "happy")
, ("cpphs", Distribution.Package.mkPackageName "cpphs")
, ("greencard", Distribution.Package.mkPackageName "greencard")
, ("c2hs", Distribution.Package.mkPackageName "c2hs")
, ("hscolour", Distribution.Package.mkPackageName "hscolour")
, ("hspec-discover", Distribution.Package.mkPackageName "hspec-discover")
, ("hsx2hs", Distribution.Package.mkPackageName "hsx2hs")
, ("gtk2hsC2hs", Distribution.Package.mkPackageName "gtk2hs-buildtools")
, ("gtk2hsHookGenerator", Distribution.Package.mkPackageName "gtk2hs-buildtools")
, ("gtk2hsTypeGen", Distribution.Package.mkPackageName "gtk2hs-buildtools")
]
-- | Executable-only packages which come pre-installed with GHC and do
-- not need to be built. Without this exception, we would either end
-- up unnecessarily rebuilding these packages, or failing because the
-- packages do not appear in the Stackage snapshot.
preInstalledPackages :: Set D.PackageName
preInstalledPackages = S.fromList
[ D.mkPackageName "hsc2hs"
, D.mkPackageName "haddock"
]
-- | Variant of 'allBuildInfo' from Cabal that, like versions before
-- 2.2, only includes buildable components.
allBuildInfo' :: PackageDescription -> [BuildInfo]
allBuildInfo' pkg_descr = [ bi | lib <- allLibraries pkg_descr
, let bi = libBuildInfo lib
, buildable bi ]
++ [ bi | flib <- foreignLibs pkg_descr
, let bi = foreignLibBuildInfo flib
, buildable bi ]
++ [ bi | exe <- executables pkg_descr
, let bi = buildInfo exe
, buildable bi ]
++ [ bi | tst <- testSuites pkg_descr
, let bi = testBuildInfo tst
, buildable bi ]
++ [ bi | tst <- benchmarks pkg_descr
, let bi = benchmarkBuildInfo tst
, buildable bi ]
-- | Get all files referenced by the package.
packageDescModulesAndFiles
:: PackageDescription
-> RIO Ctx (Map NamedComponent (Map ModuleName (Path Abs File)), Map NamedComponent [DotCabalPath], Set (Path Abs File), [PackageWarning])
packageDescModulesAndFiles pkg = do
(libraryMods,libDotCabalFiles,libWarnings) <-
maybe
(return (M.empty, M.empty, []))
(asModuleAndFileMap libComponent libraryFiles)
(library pkg)
(subLibrariesMods,subLibDotCabalFiles,subLibWarnings) <-
liftM
foldTuples
(mapM
(asModuleAndFileMap internalLibComponent libraryFiles)
(subLibraries pkg))
(executableMods,exeDotCabalFiles,exeWarnings) <-
liftM
foldTuples
(mapM
(asModuleAndFileMap exeComponent executableFiles)
(executables pkg))
(testMods,testDotCabalFiles,testWarnings) <-
liftM
foldTuples
(mapM (asModuleAndFileMap testComponent testFiles) (testSuites pkg))
(benchModules,benchDotCabalPaths,benchWarnings) <-
liftM
foldTuples
(mapM
(asModuleAndFileMap benchComponent benchmarkFiles)
(benchmarks pkg))
dfiles <- resolveGlobFiles (specVersion pkg)
(extraSrcFiles pkg
++ map (dataDir pkg FilePath.</>) (dataFiles pkg))
let modules = libraryMods <> subLibrariesMods <> executableMods <> testMods <> benchModules
files =
libDotCabalFiles <> subLibDotCabalFiles <> exeDotCabalFiles <> testDotCabalFiles <>
benchDotCabalPaths
warnings = libWarnings <> subLibWarnings <> exeWarnings <> testWarnings <> benchWarnings
return (modules, files, dfiles, warnings)
where
libComponent = const CLib
internalLibComponent = CInternalLib . T.pack . maybe "" Cabal.unUnqualComponentName . libName
exeComponent = CExe . T.pack . Cabal.unUnqualComponentName . exeName
testComponent = CTest . T.pack . Cabal.unUnqualComponentName . testName
benchComponent = CBench . T.pack . Cabal.unUnqualComponentName . benchmarkName
asModuleAndFileMap label f lib = do
(a,b,c) <- f (label lib) lib
return (M.singleton (label lib) a, M.singleton (label lib) b, c)
foldTuples = foldl' (<>) (M.empty, M.empty, [])
-- | Resolve globbing of files (e.g. data files) to absolute paths.
resolveGlobFiles
:: Version -- ^ cabal file version
-> [String]
-> RIO Ctx (Set (Path Abs File))
resolveGlobFiles cabalFileVersion =
liftM (S.fromList . catMaybes . concat) .
mapM resolve
where
resolve name =
if '*' `elem` name
then explode name
else liftM return (resolveFileOrWarn name)
explode name = do
dir <- asks (parent . ctxFile)
names <-
matchDirFileGlob'
(FL.toFilePath dir)
name
mapM resolveFileOrWarn names
matchDirFileGlob' dir glob =
catch
(liftIO (matchDirFileGlob minBound cabalFileVersion dir glob))
(\(e :: IOException) ->
if isUserError e
then do
prettyWarnL
[ flow "Wildcard does not match any files:"
, style File $ fromString glob
, line <> flow "in directory:"
, style Dir $ fromString dir
]
return []
else throwIO e)
-- | Get all files referenced by the benchmark.
benchmarkFiles
:: NamedComponent
-> Benchmark
-> RIO Ctx (Map ModuleName (Path Abs File), [DotCabalPath], [PackageWarning])
benchmarkFiles component bench = do
resolveComponentFiles component build names
where
names = bnames <> exposed
exposed =
case benchmarkInterface bench of
BenchmarkExeV10 _ fp -> [DotCabalMain fp]
BenchmarkUnsupported _ -> []
bnames = map DotCabalModule (otherModules build)
build = benchmarkBuildInfo bench
-- | Get all files referenced by the test.
testFiles
:: NamedComponent
-> TestSuite
-> RIO Ctx (Map ModuleName (Path Abs File), [DotCabalPath], [PackageWarning])
testFiles component test = do
resolveComponentFiles component build names
where
names = bnames <> exposed
exposed =
case testInterface test of
TestSuiteExeV10 _ fp -> [DotCabalMain fp]
TestSuiteLibV09 _ mn -> [DotCabalModule mn]
TestSuiteUnsupported _ -> []
bnames = map DotCabalModule (otherModules build)
build = testBuildInfo test
-- | Get all files referenced by the executable.
executableFiles
:: NamedComponent
-> Executable
-> RIO Ctx (Map ModuleName (Path Abs File), [DotCabalPath], [PackageWarning])
executableFiles component exe = do
resolveComponentFiles component build names
where
build = buildInfo exe
names =
map DotCabalModule (otherModules build) ++
[DotCabalMain (modulePath exe)]
-- | Get all files referenced by the library.
libraryFiles
:: NamedComponent
-> Library
-> RIO Ctx (Map ModuleName (Path Abs File), [DotCabalPath], [PackageWarning])
libraryFiles component lib = do
resolveComponentFiles component build names
where
build = libBuildInfo lib
names = bnames ++ exposed
exposed = map DotCabalModule (exposedModules lib)
bnames = map DotCabalModule (otherModules build)
-- | Get all files referenced by the component.
resolveComponentFiles
:: NamedComponent
-> BuildInfo
-> [DotCabalDescriptor]
-> RIO Ctx (Map ModuleName (Path Abs File), [DotCabalPath], [PackageWarning])
resolveComponentFiles component build names = do
dirs <- mapMaybeM resolveDirOrWarn (hsSourceDirs build)
dir <- asks (parent . ctxFile)
(modules,files,warnings) <-
resolveFilesAndDeps
component
(if null dirs then [dir] else dirs)
names
cfiles <- buildOtherSources build
return (modules, files <> cfiles, warnings)
-- | Get all C sources and extra source files in a build.
buildOtherSources :: BuildInfo -> RIO Ctx [DotCabalPath]
buildOtherSources build = do
cwd <- liftIO getCurrentDir
dir <- asks (parent . ctxFile)
file <- asks ctxFile
let resolveDirFiles files toCabalPath =
forMaybeM files $ \fp -> do
result <- resolveDirFile dir fp
case result of
Nothing -> do
warnMissingFile "File" cwd fp file
return Nothing
Just p -> return $ Just (toCabalPath p)
csources <- resolveDirFiles (cSources build) DotCabalCFilePath
jsources <- resolveDirFiles (targetJsSources build) DotCabalFilePath
return (csources <> jsources)
-- | Get the target's JS sources.
targetJsSources :: BuildInfo -> [FilePath]
targetJsSources = jsSources
-- | A pair of package descriptions: one which modified the buildable
-- values of test suites and benchmarks depending on whether they are
-- enabled, and one which does not.
--
-- Fields are intentionally lazy, we may only need one or the other
-- value.
--
-- MSS 2017-08-29: The very presence of this data type is terribly
-- ugly, it represents the fact that the Cabal 2.0 upgrade did _not_
-- go well. Specifically, we used to have a field to indicate whether
-- a component was enabled in addition to buildable, but that's gone
-- now, and this is an ugly proxy. We should at some point clean up
-- the mess of Package, LocalPackage, etc, and probably pull in the
-- definition of PackageDescription from Cabal with our additionally
-- needed metadata. But this is a good enough hack for the
-- moment. Odds are, you're reading this in the year 2024 and thinking
-- "wtf?"
data PackageDescriptionPair = PackageDescriptionPair
{ pdpOrigBuildable :: PackageDescription
, pdpModifiedBuildable :: PackageDescription
}
-- | Evaluates the conditions of a 'GenericPackageDescription', yielding
-- a resolved 'PackageDescription'.
resolvePackageDescription :: PackageConfig
-> GenericPackageDescription
-> PackageDescriptionPair
resolvePackageDescription packageConfig (GenericPackageDescription desc defaultFlags mlib subLibs foreignLibs' exes tests benches) =
PackageDescriptionPair
{ pdpOrigBuildable = go False
, pdpModifiedBuildable = go True
}
where
go modBuildable =
desc {library =
fmap (resolveConditions rc updateLibDeps) mlib
,subLibraries =
map (\(n, v) -> (resolveConditions rc updateLibDeps v){libName=Just n})
subLibs
,foreignLibs =
map (\(n, v) -> (resolveConditions rc updateForeignLibDeps v){foreignLibName=n})
foreignLibs'
,executables =
map (\(n, v) -> (resolveConditions rc updateExeDeps v){exeName=n})
exes
,testSuites =
map (\(n,v) -> (resolveConditions rc (updateTestDeps modBuildable) v){testName=n})
tests
,benchmarks =
map (\(n,v) -> (resolveConditions rc (updateBenchmarkDeps modBuildable) v){benchmarkName=n})
benches}
flags =
M.union (packageConfigFlags packageConfig)
(flagMap defaultFlags)
rc = mkResolveConditions
(packageConfigCompilerVersion packageConfig)
(packageConfigPlatform packageConfig)
flags
updateLibDeps lib deps =
lib {libBuildInfo =
(libBuildInfo lib) {targetBuildDepends = deps}}
updateForeignLibDeps lib deps =
lib {foreignLibBuildInfo =
(foreignLibBuildInfo lib) {targetBuildDepends = deps}}
updateExeDeps exe deps =
exe {buildInfo =
(buildInfo exe) {targetBuildDepends = deps}}
-- Note that, prior to moving to Cabal 2.0, we would set
-- testEnabled/benchmarkEnabled here. These fields no longer
-- exist, so we modify buildable instead here. The only
-- wrinkle in the Cabal 2.0 story is
-- https://github.com/haskell/cabal/issues/1725, where older
-- versions of Cabal (which may be used for actually building
-- code) don't properly exclude build-depends for
-- non-buildable components. Testing indicates that everything
-- is working fine, and that this comment can be completely
-- ignored. I'm leaving the comment anyway in case something
-- breaks and you, poor reader, are investigating.
updateTestDeps modBuildable test deps =
let bi = testBuildInfo test
bi' = bi
{ targetBuildDepends = deps
, buildable = buildable bi && (if modBuildable then packageConfigEnableTests packageConfig else True)
}
in test { testBuildInfo = bi' }
updateBenchmarkDeps modBuildable benchmark deps =
let bi = benchmarkBuildInfo benchmark
bi' = bi
{ targetBuildDepends = deps
, buildable = buildable bi && (if modBuildable then packageConfigEnableBenchmarks packageConfig else True)
}
in benchmark { benchmarkBuildInfo = bi' }
-- | Make a map from a list of flag specifications.
--
-- What is @flagManual@ for?
flagMap :: [Flag] -> Map FlagName Bool
flagMap = M.fromList . map pair
where pair :: Flag -> (FlagName, Bool)
pair = flagName &&& flagDefault
data ResolveConditions = ResolveConditions
{ rcFlags :: Map FlagName Bool
, rcCompilerVersion :: ActualCompiler
, rcOS :: OS
, rcArch :: Arch
}
-- | Generic a @ResolveConditions@ using sensible defaults.
mkResolveConditions :: ActualCompiler -- ^ Compiler version
-> Platform -- ^ installation target platform
-> Map FlagName Bool -- ^ enabled flags
-> ResolveConditions
mkResolveConditions compilerVersion (Platform arch os) flags = ResolveConditions
{ rcFlags = flags
, rcCompilerVersion = compilerVersion
, rcOS = os
, rcArch = arch
}
-- | Resolve the condition tree for the library.
resolveConditions :: (Semigroup target,Monoid target,Show target)
=> ResolveConditions
-> (target -> cs -> target)
-> CondTree ConfVar cs target
-> target
resolveConditions rc addDeps (CondNode lib deps cs) = basic <> children
where basic = addDeps lib deps
children = mconcat (map apply cs)
where apply (Cabal.CondBranch cond node mcs) =
if condSatisfied cond
then resolveConditions rc addDeps node
else maybe mempty (resolveConditions rc addDeps) mcs
condSatisfied c =
case c of
Var v -> varSatisifed v
Lit b -> b
CNot c' ->
not (condSatisfied c')
COr cx cy ->
condSatisfied cx || condSatisfied cy
CAnd cx cy ->
condSatisfied cx && condSatisfied cy
varSatisifed v =
case v of
OS os -> os == rcOS rc
Arch arch -> arch == rcArch rc
Flag flag ->
fromMaybe False $ M.lookup flag (rcFlags rc)
-- NOTE: ^^^^^ This should never happen, as all flags
-- which are used must be declared. Defaulting to
-- False.
Impl flavor range ->
case (flavor, rcCompilerVersion rc) of
(GHC, ACGhc vghc) -> vghc `withinRange` range
(GHC, ACGhcjs _ vghc) -> vghc `withinRange` range
(GHCJS, ACGhcjs vghcjs _) ->
vghcjs `withinRange` range
_ -> False
-- | Get the name of a dependency.
depName :: Dependency -> PackageName
depName (Dependency n _) = n
-- | Get the version range of a dependency.
depRange :: Dependency -> VersionRange
depRange (Dependency _ r) = r
-- | Try to resolve the list of base names in the given directory by
-- looking for unique instances of base names applied with the given
-- extensions, plus find any of their module and TemplateHaskell
-- dependencies.