-
Notifications
You must be signed in to change notification settings - Fork 698
/
ProjectConfig.hs
1800 lines (1656 loc) · 64.8 KB
/
ProjectConfig.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 DeriveDataTypeable #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeApplications #-}
-- | Handling project configuration.
module Distribution.Client.ProjectConfig
( -- * Types for project config
ProjectConfig (..)
, ProjectConfigToParse (..)
, ProjectConfigBuildOnly (..)
, ProjectConfigShared (..)
, ProjectConfigProvenance (..)
, PackageConfig (..)
, MapLast (..)
, MapMappend (..)
-- * Project root
, findProjectRoot
, getProjectRootUsability
, ProjectRoot (..)
, BadProjectRoot (..)
, ProjectRootUsability (..)
-- * Project config files
, readProjectConfig
, readGlobalConfig
, readProjectLocalExtraConfig
, readProjectLocalFreezeConfig
, reportParseResult
, showProjectConfig
, withGlobalConfig
, withProjectOrGlobalConfig
, writeProjectLocalExtraConfig
, writeProjectLocalFreezeConfig
, writeProjectConfigFile
, commandLineFlagsToProjectConfig
, onlyTopLevelProvenance
-- * Packages within projects
, ProjectPackageLocation (..)
, BadPackageLocations (..)
, BadPackageLocation (..)
, BadPackageLocationMatch (..)
, findProjectPackages
, fetchAndReadSourcePackages
-- * Resolving configuration
, lookupLocalPackageConfig
, projectConfigWithBuilderRepoContext
, projectConfigWithSolverRepoContext
, SolverSettings (..)
, resolveSolverSettings
, BuildTimeSettings (..)
, resolveBuildTimeSettings
, resolveNumJobsSetting
-- * Checking configuration
, checkBadPerPackageCompilerPaths
, BadPerPackageCompilerPaths (..)
-- * Globals
, maxNumFetchJobs
) where
import Distribution.Client.Compat.Prelude
import Text.PrettyPrint (nest, render, text, vcat)
import Prelude ()
import Distribution.Client.Glob
( isTrivialRootedGlob
)
import Distribution.Client.JobControl
import Distribution.Client.ProjectConfig.Legacy
import Distribution.Client.ProjectConfig.Types
import Distribution.Client.RebuildMonad
import Distribution.Client.VCS
( SourceRepoProblem (..)
, VCS (..)
, configureVCS
, knownVCSs
, syncSourceRepos
, validateSourceRepos
)
import Distribution.Client.BuildReports.Types
( ReportLevel (..)
)
import Distribution.Client.Config
( getConfigFilePath
, loadConfig
)
import Distribution.Client.DistDirLayout
( CabalDirLayout (..)
, DistDirLayout (..)
, ProjectRoot (..)
, defaultProjectFile
)
import Distribution.Client.GlobalFlags
( RepoContext (..)
, withRepoContext'
)
import Distribution.Client.HashValue
import Distribution.Client.HttpUtils
( HttpTransport
, configureTransport
, downloadURI
, transportCheckHttps
)
import Distribution.Client.Types
import Distribution.Client.Utils.Parsec (renderParseError)
import Distribution.Solver.Types.ConstraintSource
import Distribution.Solver.Types.PackageConstraint
import Distribution.Solver.Types.Settings
import Distribution.Solver.Types.SourcePackage
import Distribution.Client.Errors
import Distribution.Client.Setup
( defaultMaxBackjumps
, defaultSolver
)
import Distribution.Client.SrcDist
( packageDirToSdist
)
import Distribution.Client.Targets
import Distribution.Client.Types.SourceRepo
( SourceRepoList
, SourceRepositoryPackage (..)
, srpFanOut
)
import Distribution.Client.Utils
( determineNumJobs
)
import qualified Distribution.Deprecated.ParseUtils as OldParser
( ParseResult (..)
, locatedErrorMsg
, showPWarning
)
import Distribution.Fields
( PError
, PWarning
, runParseResult
, showPWarning
)
import Distribution.Package
import Distribution.PackageDescription.Parsec
( parseGenericPackageDescription
)
import Distribution.Simple.Compiler
( Compiler
, compilerInfo
)
import Distribution.Simple.InstallDirs
( PathTemplate
, fromPathTemplate
, initialPathTemplateEnv
, substPathTemplate
, toPathTemplate
)
import Distribution.Simple.Program
( ConfiguredProgram (..)
)
import Distribution.Simple.Setup
( Flag (Flag)
, flagToList
, flagToMaybe
, fromFlag
, fromFlagOrDefault
, toFlag
)
import Distribution.Simple.Utils
( createDirectoryIfMissingVerbose
, dieWithException
, info
, maybeExit
, notice
, rawSystemIOWithEnv
, warn
)
import Distribution.System
( Platform
)
import Distribution.Types.GenericPackageDescription
( GenericPackageDescription
)
import Distribution.Types.PackageVersionConstraint
( PackageVersionConstraint (..)
)
import Distribution.Types.SourceRepo
( RepoType (..)
)
import Distribution.Utils.Generic
( toUTF8BS
, toUTF8LBS
)
import Distribution.Utils.NubList
( fromNubList
)
import Distribution.Verbosity
( modifyVerbosity
, verbose
)
import Distribution.Version
import qualified Codec.Archive.Tar as Tar
import qualified Codec.Archive.Tar.Entry as Tar
import qualified Distribution.Client.GZipUtils as GZipUtils
import qualified Distribution.Client.Tar as Tar
import Control.Exception (handle)
import Control.Monad.Trans (liftIO)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import qualified Data.List.NonEmpty as NE
import qualified Data.Map as Map
import qualified Data.Set as Set
import Network.URI
( URI (..)
, URIAuth (..)
, parseAbsoluteURI
, uriToString
)
import System.Directory
( canonicalizePath
, doesDirectoryExist
, doesFileExist
, doesPathExist
, getCurrentDirectory
, getDirectoryContents
, getHomeDirectory
, pathIsSymbolicLink
)
import System.FilePath hiding (combine)
import System.IO
( IOMode (ReadMode)
, withBinaryFile
)
import Distribution.Solver.Types.ProjectConfigPath
----------------------------------------
-- Resolving configuration to settings
--
-- | Look up a 'PackageConfig' field in the 'ProjectConfig' for a specific
-- 'PackageName'. This returns the configuration that applies to all local
-- packages plus any package-specific configuration for this package.
lookupLocalPackageConfig
:: (Semigroup a, Monoid a)
=> (PackageConfig -> a)
-> ProjectConfig
-> PackageName
-> a
lookupLocalPackageConfig
field
ProjectConfig
{ projectConfigLocalPackages
, projectConfigSpecificPackage
}
pkgname =
field projectConfigLocalPackages
<> maybe
mempty
field
(Map.lookup pkgname (getMapMappend projectConfigSpecificPackage))
-- | Use a 'RepoContext' based on the 'BuildTimeSettings'.
projectConfigWithBuilderRepoContext
:: Verbosity
-> BuildTimeSettings
-> (RepoContext -> IO a)
-> IO a
projectConfigWithBuilderRepoContext verbosity BuildTimeSettings{..} =
withRepoContext'
verbosity
buildSettingRemoteRepos
buildSettingLocalNoIndexRepos
buildSettingCacheDir
buildSettingHttpTransport
(Just buildSettingIgnoreExpiry)
buildSettingProgPathExtra
-- | Use a 'RepoContext', but only for the solver. The solver does not use the
-- full facilities of the 'RepoContext' so we can get away with making one
-- that doesn't have an http transport. And that avoids having to have access
-- to the 'BuildTimeSettings'
projectConfigWithSolverRepoContext
:: Verbosity
-> ProjectConfigShared
-> ProjectConfigBuildOnly
-> (RepoContext -> IO a)
-> IO a
projectConfigWithSolverRepoContext
verbosity
ProjectConfigShared{..}
ProjectConfigBuildOnly{..} =
withRepoContext'
verbosity
(fromNubList projectConfigRemoteRepos)
(fromNubList projectConfigLocalNoIndexRepos)
( fromFlagOrDefault
( error
"projectConfigWithSolverRepoContext: projectConfigCacheDir"
)
projectConfigCacheDir
)
(flagToMaybe projectConfigHttpTransport)
(flagToMaybe projectConfigIgnoreExpiry)
(fromNubList projectConfigProgPathExtra)
-- | Resolve the project configuration, with all its optional fields, into
-- 'SolverSettings' with no optional fields (by applying defaults).
resolveSolverSettings :: ProjectConfig -> SolverSettings
resolveSolverSettings
ProjectConfig
{ projectConfigShared
, projectConfigLocalPackages
, projectConfigSpecificPackage
} =
SolverSettings{..}
where
-- TODO: [required eventually] some of these settings need validation, e.g.
-- the flag assignments need checking.
cabalPkgname = mkPackageName "Cabal"
profilingDynamicConstraint =
( UserConstraint
(UserAnySetupQualifier cabalPkgname)
(PackagePropertyVersion $ orLaterVersion (mkVersion [3, 13, 0]))
, ConstraintSourceProfiledDynamic
)
profDynEnabledGlobally = fromFlagOrDefault False (packageConfigProfShared projectConfigLocalPackages)
profDynEnabledAnyLocally =
or
[ fromFlagOrDefault False (packageConfigProfShared ppc)
| (_, ppc) <- Map.toList (getMapMappend projectConfigSpecificPackage)
]
-- Add a setup.Cabal >= 3.13 constraint if prof+dyn is enabled globally
-- or any package in the project enables it.
-- Ideally we'd apply this constraint only on the closure of packages requiring prof+dyn,
-- but that would require another solver run for marginal advantages that
-- will further shrink as 3.13 is adopted.
solverCabalLibConstraints =
[profilingDynamicConstraint | profDynEnabledGlobally || profDynEnabledAnyLocally]
solverSettingRemoteRepos = fromNubList projectConfigRemoteRepos
solverSettingLocalNoIndexRepos = fromNubList projectConfigLocalNoIndexRepos
solverSettingConstraints = solverCabalLibConstraints ++ projectConfigConstraints
solverSettingPreferences = projectConfigPreferences
solverSettingFlagAssignment = packageConfigFlagAssignment projectConfigLocalPackages
solverSettingFlagAssignments =
fmap
packageConfigFlagAssignment
(getMapMappend projectConfigSpecificPackage)
solverSettingCabalVersion = flagToMaybe projectConfigCabalVersion
solverSettingSolver = fromFlag projectConfigSolver
solverSettingAllowOlder = fromMaybe mempty projectConfigAllowOlder
solverSettingAllowNewer = fromMaybe mempty projectConfigAllowNewer
solverSettingMaxBackjumps = case fromFlag projectConfigMaxBackjumps of
n
| n < 0 -> Nothing
| otherwise -> Just n
solverSettingReorderGoals = fromFlag projectConfigReorderGoals
solverSettingCountConflicts = fromFlag projectConfigCountConflicts
solverSettingFineGrainedConflicts = fromFlag projectConfigFineGrainedConflicts
solverSettingMinimizeConflictSet = fromFlag projectConfigMinimizeConflictSet
solverSettingStrongFlags = fromFlag projectConfigStrongFlags
solverSettingAllowBootLibInstalls = fromFlag projectConfigAllowBootLibInstalls
solverSettingOnlyConstrained = fromFlag projectConfigOnlyConstrained
solverSettingIndexState = flagToMaybe projectConfigIndexState
solverSettingActiveRepos = flagToMaybe projectConfigActiveRepos
solverSettingIndependentGoals = fromFlag projectConfigIndependentGoals
solverSettingPreferOldest = fromFlag projectConfigPreferOldest
-- solverSettingShadowPkgs = fromFlag projectConfigShadowPkgs
-- solverSettingReinstall = fromFlag projectConfigReinstall
-- solverSettingAvoidReinstalls = fromFlag projectConfigAvoidReinstalls
-- solverSettingOverrideReinstall = fromFlag projectConfigOverrideReinstall
-- solverSettingUpgradeDeps = fromFlag projectConfigUpgradeDeps
ProjectConfigShared{..} = defaults <> projectConfigShared
defaults =
mempty
{ projectConfigSolver = Flag defaultSolver
, projectConfigAllowOlder = Just (AllowOlder mempty)
, projectConfigAllowNewer = Just (AllowNewer mempty)
, projectConfigMaxBackjumps = Flag defaultMaxBackjumps
, projectConfigReorderGoals = Flag (ReorderGoals False)
, projectConfigCountConflicts = Flag (CountConflicts True)
, projectConfigFineGrainedConflicts = Flag (FineGrainedConflicts True)
, projectConfigMinimizeConflictSet = Flag (MinimizeConflictSet False)
, projectConfigStrongFlags = Flag (StrongFlags False)
, projectConfigAllowBootLibInstalls = Flag (AllowBootLibInstalls False)
, projectConfigOnlyConstrained = Flag OnlyConstrainedNone
, projectConfigIndependentGoals = Flag (IndependentGoals False)
, projectConfigPreferOldest = Flag (PreferOldest False)
-- projectConfigShadowPkgs = Flag False,
-- projectConfigReinstall = Flag False,
-- projectConfigAvoidReinstalls = Flag False,
-- projectConfigOverrideReinstall = Flag False,
-- projectConfigUpgradeDeps = Flag False
}
-- | Resolve the project configuration, with all its optional fields, into
-- 'BuildTimeSettings' with no optional fields (by applying defaults).
resolveBuildTimeSettings
:: Verbosity
-> CabalDirLayout
-> ProjectConfig
-> BuildTimeSettings
resolveBuildTimeSettings
verbosity
CabalDirLayout
{ cabalLogsDirectory
}
ProjectConfig
{ projectConfigShared =
ProjectConfigShared
{ projectConfigRemoteRepos
, projectConfigLocalNoIndexRepos
, projectConfigProgPathExtra
}
, projectConfigBuildOnly
} =
BuildTimeSettings{..}
where
buildSettingDryRun = fromFlag projectConfigDryRun
buildSettingOnlyDeps = fromFlag projectConfigOnlyDeps
buildSettingOnlyDownload = fromFlag projectConfigOnlyDownload
buildSettingSummaryFile = fromNubList projectConfigSummaryFile
-- buildSettingLogFile -- defined below, more complicated
-- buildSettingLogVerbosity -- defined below, more complicated
buildSettingBuildReports = fromFlag projectConfigBuildReports
buildSettingSymlinkBinDir = flagToList projectConfigSymlinkBinDir
buildSettingNumJobs = resolveNumJobsSetting projectConfigUseSemaphore projectConfigNumJobs
buildSettingKeepGoing = fromFlag projectConfigKeepGoing
buildSettingOfflineMode = fromFlag projectConfigOfflineMode
buildSettingKeepTempFiles = fromFlag projectConfigKeepTempFiles
buildSettingRemoteRepos = fromNubList projectConfigRemoteRepos
buildSettingLocalNoIndexRepos = fromNubList projectConfigLocalNoIndexRepos
buildSettingCacheDir = fromFlag projectConfigCacheDir
buildSettingHttpTransport = flagToMaybe projectConfigHttpTransport
buildSettingIgnoreExpiry = fromFlag projectConfigIgnoreExpiry
buildSettingReportPlanningFailure =
fromFlag projectConfigReportPlanningFailure
buildSettingProgPathExtra = fromNubList projectConfigProgPathExtra
buildSettingHaddockOpen = False
ProjectConfigBuildOnly{..} =
defaults
<> projectConfigBuildOnly
defaults =
mempty
{ projectConfigDryRun = toFlag False
, projectConfigOnlyDeps = toFlag False
, projectConfigOnlyDownload = toFlag False
, projectConfigBuildReports = toFlag NoReports
, projectConfigReportPlanningFailure = toFlag False
, projectConfigKeepGoing = toFlag False
, projectConfigOfflineMode = toFlag False
, projectConfigKeepTempFiles = toFlag False
, projectConfigIgnoreExpiry = toFlag False
}
-- The logging logic: what log file to use and what verbosity.
--
-- If the user has specified --remote-build-reporting=detailed, use the
-- default log file location. If the --build-log option is set, use the
-- provided location. Otherwise don't use logging, unless building in
-- parallel (in which case the default location is used).
--
buildSettingLogFile
:: Maybe
( Compiler
-> Platform
-> PackageId
-> UnitId
-> FilePath
)
buildSettingLogFile
| useDefaultTemplate = Just (substLogFileName defaultTemplate)
| otherwise = fmap substLogFileName givenTemplate
defaultTemplate =
toPathTemplate $
cabalLogsDirectory
</> "$compiler"
</> "$libname"
<.> "log"
givenTemplate = flagToMaybe projectConfigLogFile
useDefaultTemplate
| buildSettingBuildReports == DetailedReports = True
| isJust givenTemplate = False
| isParallelBuild buildSettingNumJobs = True
| otherwise = False
substLogFileName
:: PathTemplate
-> Compiler
-> Platform
-> PackageId
-> UnitId
-> FilePath
substLogFileName template compiler platform pkgid uid =
fromPathTemplate (substPathTemplate env template)
where
env =
initialPathTemplateEnv
pkgid
uid
(compilerInfo compiler)
platform
-- If the user has specified --remote-build-reporting=detailed or
-- --build-log, use more verbose logging.
--
buildSettingLogVerbosity :: Verbosity
buildSettingLogVerbosity
| overrideVerbosity = modifyVerbosity (max verbose) verbosity
| otherwise = verbosity
overrideVerbosity :: Bool
overrideVerbosity
| buildSettingBuildReports == DetailedReports = True
| isJust givenTemplate = True
| isParallelBuild buildSettingNumJobs = False
| otherwise = False
-- | Determine the number of jobs (ParStrat) from the project config
resolveNumJobsSetting
:: Flag Bool
-- ^ Whether to use a semaphore (-jsem)
-> Flag (Maybe Int)
-- ^ The number of jobs to run concurrently
-> ParStratX Int
resolveNumJobsSetting projectConfigUseSemaphore projectConfigNumJobs =
if fromFlag projectConfigUseSemaphore
then UseSem (determineNumJobs projectConfigNumJobs)
else case (determineNumJobs projectConfigNumJobs) of
1 -> Serial
n -> NumJobs (Just n)
---------------------------------------------
-- Reading and writing project config files
--
-- | Get @ProjectRootUsability@ of a given file
getProjectRootUsability :: FilePath -> IO ProjectRootUsability
getProjectRootUsability filePath = do
exists <- doesFileExist filePath
if exists
then return ProjectRootUsabilityPresentAndUsable
else do
let isUsableAction =
handle @IOException
-- NOTE: if any IOException is raised, we assume the file does not exist.
-- That is what happen when we call @pathIsSymbolicLink@ on a @FilePath@ that does not exist.
(const $ pure False)
((||) <$> pathIsSymbolicLink filePath <*> doesPathExist filePath)
isUnusable <- isUsableAction
if isUnusable
then return ProjectRootUsabilityPresentAndUnusable
else return ProjectRootUsabilityNotPresent
-- | Find the root of this project.
--
-- The project directory will be one of the following:
-- 1. @mprojectDir@ when present
-- 2. The first directory containing @mprojectFile@/@cabal.project@, starting from the current directory
-- and recursively checking parent directories
-- 3. The current directory
findProjectRoot
:: Verbosity
-> Maybe FilePath
-- ^ Explicit project directory
-> Maybe FilePath
-- ^ Explicit project file
-> IO (Either BadProjectRoot ProjectRoot)
findProjectRoot verbosity mprojectDir mprojectFile = do
case mprojectDir of
Nothing
| Just file <- mprojectFile
, isAbsolute file -> do
warn verbosity $
"Specifying an absolute path to the project file is deprecated."
<> " Use --project-dir to set the project's directory."
getProjectRootUsability file >>= \case
ProjectRootUsabilityPresentAndUsable ->
uncurry projectRoot
=<< first dropTrailingPathSeparator . splitFileName <$> canonicalizePath file
ProjectRootUsabilityNotPresent ->
left (BadProjectRootExplicitFileNotFound file)
ProjectRootUsabilityPresentAndUnusable ->
left (BadProjectRootFileBroken file)
| otherwise -> probeProjectRoot mprojectFile
Just dir ->
doesDirectoryExist dir >>= \case
False -> left (BadProjectRootDirNotFound dir)
True -> do
projectDir <- canonicalizePath dir
case mprojectFile of
Nothing -> pure $ Right (ProjectRootExplicit projectDir defaultProjectFile)
Just projectFile
| isAbsolute projectFile ->
getProjectRootUsability projectFile >>= \case
ProjectRootUsabilityNotPresent ->
left (BadProjectRootAbsoluteFileNotFound projectFile)
ProjectRootUsabilityPresentAndUsable ->
Right . ProjectRootExplicitAbsolute dir <$> canonicalizePath projectFile
ProjectRootUsabilityPresentAndUnusable ->
left (BadProjectRootFileBroken projectFile)
| otherwise ->
getProjectRootUsability (projectDir </> projectFile) >>= \case
ProjectRootUsabilityNotPresent ->
left (BadProjectRootDirFileNotFound dir projectFile)
ProjectRootUsabilityPresentAndUsable ->
projectRoot projectDir projectFile
ProjectRootUsabilityPresentAndUnusable ->
left (BadProjectRootFileBroken projectFile)
where
left = pure . Left
projectRoot projectDir projectFile =
pure $ Right (ProjectRootExplicit projectDir projectFile)
probeProjectRoot :: Maybe FilePath -> IO (Either BadProjectRoot ProjectRoot)
probeProjectRoot mprojectFile = do
startdir <- System.Directory.getCurrentDirectory
homedir <- getHomeDirectory
probe startdir homedir
where
projectFileName :: String
projectFileName = fromMaybe defaultProjectFile mprojectFile
-- Search upwards. If we get to the users home dir or the filesystem root,
-- then use the current dir
probe :: FilePath -> String -> IO (Either BadProjectRoot ProjectRoot)
probe startdir homedir = go startdir
where
go :: FilePath -> IO (Either BadProjectRoot ProjectRoot)
go dir | isDrive dir || dir == homedir =
case mprojectFile of
Nothing -> return (Right (ProjectRootImplicit startdir))
Just file -> return (Left (BadProjectRootExplicitFileNotFound file))
go dir = do
getProjectRootUsability (dir </> projectFileName) >>= \case
ProjectRootUsabilityNotPresent ->
go (takeDirectory dir)
ProjectRootUsabilityPresentAndUsable ->
return (Right $ ProjectRootExplicit dir projectFileName)
ProjectRootUsabilityPresentAndUnusable ->
return (Left $ BadProjectRootFileBroken projectFileName)
-- | Errors returned by 'findProjectRoot'.
data BadProjectRoot
= BadProjectRootExplicitFileNotFound FilePath
| BadProjectRootDirNotFound FilePath
| BadProjectRootAbsoluteFileNotFound FilePath
| BadProjectRootDirFileNotFound FilePath FilePath
| BadProjectRootFileBroken FilePath
deriving (Show, Typeable, Eq)
instance Exception BadProjectRoot where
displayException = renderBadProjectRoot
renderBadProjectRoot :: BadProjectRoot -> String
renderBadProjectRoot = \case
BadProjectRootExplicitFileNotFound projectFile ->
"The given project file '" ++ projectFile ++ "' does not exist."
BadProjectRootDirNotFound dir ->
"The given project directory '" <> dir <> "' does not exist."
BadProjectRootAbsoluteFileNotFound file ->
"The given project file '" <> file <> "' does not exist."
BadProjectRootDirFileNotFound dir file ->
"The given project directory/file combination '" <> dir </> file <> "' does not exist."
BadProjectRootFileBroken file ->
"The given project file '" <> file <> "' is broken. Is it a broken symbolic link?"
-- | State of the project file, encodes if the file can be used
data ProjectRootUsability
= -- | The file is present and can be used
ProjectRootUsabilityPresentAndUsable
| -- | The file is present but can't be used (e.g. broken symlink)
ProjectRootUsabilityPresentAndUnusable
| -- | The file is not present
ProjectRootUsabilityNotPresent
deriving (Eq, Show)
withGlobalConfig
:: Verbosity
-- ^ verbosity
-> Flag FilePath
-- ^ @--cabal-config@
-> (ProjectConfig -> IO a)
-- ^ with global
-> IO a
withGlobalConfig verbosity gcf with = do
globalConfig <- runRebuild "" $ readGlobalConfig verbosity gcf
with globalConfig
withProjectOrGlobalConfig
:: Flag Bool
-- ^ whether to ignore local project (--ignore-project flag)
-> IO a
-- ^ continuation with project
-> IO a
-- ^ continuation without project
-> IO a
withProjectOrGlobalConfig (Flag True) _with without = do
without
withProjectOrGlobalConfig _ignorePrj with without =
withProjectOrGlobalConfig' with without
withProjectOrGlobalConfig'
:: IO a
-- ^ continuation with project
-> IO a
-- ^ continuation without project
-> IO a
withProjectOrGlobalConfig' with without = do
catch with $
\case
(BadPackageLocations prov locs)
| prov == Set.singleton Implicit
, let
isGlobErr (BadLocGlobEmptyMatch _) = True
isGlobErr _ = False
, any isGlobErr locs -> do
without
err -> throwIO err
-- | Read all the config relevant for a project. This includes the project
-- file if any, plus other global config.
readProjectConfig
:: Verbosity
-> HttpTransport
-> Flag Bool
-- ^ @--ignore-project@
-> Flag FilePath
-> DistDirLayout
-> Rebuild ProjectConfigSkeleton
readProjectConfig verbosity _ (Flag True) configFileFlag _ = do
global <- singletonProjectConfigSkeleton <$> readGlobalConfig verbosity configFileFlag
return (global <> singletonProjectConfigSkeleton defaultImplicitProjectConfig)
readProjectConfig verbosity httpTransport _ configFileFlag distDirLayout = do
global <- singletonProjectConfigSkeleton <$> readGlobalConfig verbosity configFileFlag
local <- readProjectLocalConfigOrDefault verbosity httpTransport distDirLayout
freeze <- readProjectLocalFreezeConfig verbosity httpTransport distDirLayout
extra <- readProjectLocalExtraConfig verbosity httpTransport distDirLayout
return (global <> local <> freeze <> extra)
-- | Reads an explicit @cabal.project@ file in the given project root dir,
-- or returns the default project config for an implicitly defined project.
readProjectLocalConfigOrDefault
:: Verbosity
-> HttpTransport
-> DistDirLayout
-> Rebuild ProjectConfigSkeleton
readProjectLocalConfigOrDefault verbosity httpTransport distDirLayout = do
let projectFile = distProjectFile distDirLayout ""
usesExplicitProjectRoot <- liftIO $ doesFileExist projectFile
if usesExplicitProjectRoot
then do
readProjectFileSkeleton verbosity httpTransport distDirLayout "" "project file"
else do
monitorFiles [monitorNonExistentFile projectFile]
return (singletonProjectConfigSkeleton defaultImplicitProjectConfig)
defaultImplicitProjectConfig :: ProjectConfig
defaultImplicitProjectConfig =
mempty
{ -- We expect a package in the current directory.
projectPackages = ["./*.cabal"]
, projectConfigProvenance = Set.singleton Implicit
}
-- | Reads a @cabal.project.local@ file in the given project root dir,
-- or returns empty. This file gets written by @cabal configure@, or in
-- principle can be edited manually or by other tools.
readProjectLocalExtraConfig
:: Verbosity
-> HttpTransport
-> DistDirLayout
-> Rebuild ProjectConfigSkeleton
readProjectLocalExtraConfig verbosity httpTransport distDirLayout =
readProjectFileSkeleton
verbosity
httpTransport
distDirLayout
"local"
"project local configuration file"
-- | Reads a @cabal.project.freeze@ file in the given project root dir,
-- or returns empty. This file gets written by @cabal freeze@, or in
-- principle can be edited manually or by other tools.
readProjectLocalFreezeConfig
:: Verbosity
-> HttpTransport
-> DistDirLayout
-> Rebuild ProjectConfigSkeleton
readProjectLocalFreezeConfig verbosity httpTransport distDirLayout =
readProjectFileSkeleton
verbosity
httpTransport
distDirLayout
"freeze"
"project freeze file"
-- | Reads a named extended (with imports and conditionals) config file in the given project root dir, or returns empty.
readProjectFileSkeleton :: Verbosity -> HttpTransport -> DistDirLayout -> String -> String -> Rebuild ProjectConfigSkeleton
readProjectFileSkeleton
verbosity
httpTransport
DistDirLayout{distProjectFile, distDownloadSrcDirectory}
extensionName
extensionDescription = do
exists <- liftIO $ doesFileExist extensionFile
if exists
then do
monitorFiles [monitorFileHashed extensionFile]
pcs <- liftIO readExtensionFile
monitorFiles $ map monitorFileHashed (projectConfigPathRoot <$> projectSkeletonImports pcs)
pure pcs
else do
monitorFiles [monitorNonExistentFile extensionFile]
return mempty
where
extensionFile = distProjectFile extensionName
readExtensionFile =
reportParseResult verbosity extensionDescription extensionFile
=<< parseProject extensionFile distDownloadSrcDirectory httpTransport verbosity . ProjectConfigToParse
=<< BS.readFile extensionFile
-- | Render the 'ProjectConfig' format.
--
-- For the moment this is implemented in terms of a pretty printer for the
-- legacy configuration types, plus a conversion.
showProjectConfig :: ProjectConfig -> String
showProjectConfig =
showLegacyProjectConfig . convertToLegacyProjectConfig
-- | Write a @cabal.project.local@ file in the given project root dir.
writeProjectLocalExtraConfig :: DistDirLayout -> ProjectConfig -> IO ()
writeProjectLocalExtraConfig DistDirLayout{distProjectFile} =
writeProjectConfigFile (distProjectFile "local")
-- | Write a @cabal.project.freeze@ file in the given project root dir.
writeProjectLocalFreezeConfig :: DistDirLayout -> ProjectConfig -> IO ()
writeProjectLocalFreezeConfig DistDirLayout{distProjectFile} =
writeProjectConfigFile (distProjectFile "freeze")
-- | Write in the @cabal.project@ format to the given file.
writeProjectConfigFile :: FilePath -> ProjectConfig -> IO ()
writeProjectConfigFile file =
writeFile file . showProjectConfig
-- | Read the user's cabal-install config file.
readGlobalConfig :: Verbosity -> Flag FilePath -> Rebuild ProjectConfig
readGlobalConfig verbosity configFileFlag = do
config <- liftIO (loadConfig verbosity configFileFlag)
configFile <- liftIO (getConfigFilePath configFileFlag)
monitorFiles [monitorFileHashed configFile]
return (convertLegacyGlobalConfig config)
reportParseResult :: Verbosity -> String -> FilePath -> OldParser.ParseResult ProjectConfigSkeleton -> IO ProjectConfigSkeleton
reportParseResult verbosity _filetype filename (OldParser.ParseOk warnings x) = do
unless (null warnings) $
let msg = unlines (map (OldParser.showPWarning (intercalate ", " $ filename : (projectConfigPathRoot <$> projectSkeletonImports x))) warnings)
in warn verbosity msg
return x
reportParseResult verbosity filetype filename (OldParser.ParseFailed err) =
let (line, msg) = OldParser.locatedErrorMsg err
errLineNo = maybe "" (\n -> ':' : show n) line
in dieWithException verbosity $ ReportParseResult filetype filename errLineNo msg
---------------------------------------------
-- Finding packages in the project
--
-- | The location of a package as part of a project. Local file paths are
-- either absolute (if the user specified it as such) or they are relative
-- to the project root.
data ProjectPackageLocation
= ProjectPackageLocalCabalFile FilePath
| ProjectPackageLocalDirectory FilePath FilePath -- dir and .cabal file
| ProjectPackageLocalTarball FilePath
| ProjectPackageRemoteTarball URI
| ProjectPackageRemoteRepo SourceRepoList
| ProjectPackageNamed PackageVersionConstraint
deriving (Show)
-- | Exception thrown by 'findProjectPackages'.
data BadPackageLocations
= BadPackageLocations (Set ProjectConfigProvenance) [BadPackageLocation]
deriving (Show, Typeable)
instance Exception BadPackageLocations where
displayException = renderBadPackageLocations
-- TODO: [nice to have] custom exception subclass for Doc rendering, colour etc
data BadPackageLocation
= BadPackageLocationFile BadPackageLocationMatch
| BadLocGlobEmptyMatch String
| BadLocGlobBadMatches String [BadPackageLocationMatch]
| BadLocUnexpectedUriScheme String
| BadLocUnrecognisedUri String
| BadLocUnrecognised String
deriving (Show)
data BadPackageLocationMatch
= BadLocUnexpectedFile String
| BadLocNonexistantFile String
| BadLocDirNoCabalFile String
| BadLocDirManyCabalFiles String
deriving (Show)
renderBadPackageLocations :: BadPackageLocations -> String
renderBadPackageLocations (BadPackageLocations provenance bpls)
-- There is no provenance information,
-- render standard bad package error information.
| Set.null provenance = renderErrors renderBadPackageLocation
-- The configuration is implicit, render bad package locations
-- using possibly specialized error messages.
| Set.singleton Implicit == provenance =
renderErrors renderImplicitBadPackageLocation
-- The configuration contains both implicit and explicit provenance.
-- This should not occur, and a message is output to assist debugging.
| Implicit `Set.member` provenance =
"Warning: both implicit and explicit configuration is present."
++ renderExplicit
-- The configuration was read from one or more explicit path(s),
-- list the locations and render the bad package error information.
-- The intent is to supersede this with the relevant location information
-- per package error.
| otherwise = renderExplicit
where
renderErrors f = unlines (map f bpls)
renderExplicit =
"When using configuration from:\n"
++ render (nest 2 . docProjectConfigFiles $ mapMaybe getExplicit (Set.toList provenance))
++ "\nThe following errors occurred:\n"
++ render (nest 2 $ vcat ((text "-" <+>) . text <$> map renderBadPackageLocation bpls))
getExplicit (Explicit path) = Just path
getExplicit Implicit = Nothing
-- TODO: [nice to have] keep track of the config file (and src loc) packages
-- were listed, to use in error messages
-- | Render bad package location error information for the implicit
-- @cabal.project@ configuration.
--
-- TODO: This is currently not fully realized, with only one of the implicit
-- cases handled. More cases should be added with informative help text
-- about the issues related specifically when having no project configuration
-- is present.
renderImplicitBadPackageLocation :: BadPackageLocation -> String
renderImplicitBadPackageLocation bpl = case bpl of
BadLocGlobEmptyMatch pkglocstr ->
"No cabal.project file or cabal file matching the default glob '"
++ pkglocstr
++ "' was found.\n"
++ "Please create a package description file <pkgname>.cabal "
++ "or a cabal.project file referencing the packages you "
++ "want to build."
_ -> renderBadPackageLocation bpl
renderBadPackageLocation :: BadPackageLocation -> String
renderBadPackageLocation bpl = case bpl of
BadPackageLocationFile badmatch ->
renderBadPackageLocationMatch badmatch
BadLocGlobEmptyMatch pkglocstr ->
"The package location glob '"
++ pkglocstr
++ "' does not match any files or directories."
BadLocGlobBadMatches pkglocstr failures ->
"The package location glob '"
++ pkglocstr
++ "' does not match any "
++ "recognised forms of package. "
++ concatMap ((' ' :) . renderBadPackageLocationMatch) failures
BadLocUnexpectedUriScheme pkglocstr ->
"The package location URI '"
++ pkglocstr
++ "' does not use a "
++ "supported URI scheme. The supported URI schemes are http, https and "