-
Notifications
You must be signed in to change notification settings - Fork 841
/
Setup.hs
3027 lines (2847 loc) · 110 KB
/
Setup.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 NoImplicitPrelude #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ViewPatterns #-}
module Stack.Setup
( setupEnv
, ensureCompilerAndMsys
, ensureDockerStackExe
, SetupOpts (..)
, defaultSetupInfoYaml
, withNewLocalBuildTargets
-- * Stack binary download
, StackReleaseInfo
, getDownloadVersion
, stackVersion
, preferredPlatforms
, downloadStackReleaseInfo
, downloadStackExe
) where
import qualified Codec.Archive.Tar as Tar
import Conduit
( ConduitT, await, concatMapMC, filterCE, foldMC, yield )
import Control.Applicative ( empty )
import Crypto.Hash ( SHA1 (..), SHA256 (..) )
import qualified Data.Aeson.KeyMap as KeyMap
import Data.Aeson.Types ( Value (..) )
import Data.Aeson.WarningParser
( WithJSONWarnings (..), logJSONWarnings )
import qualified Data.Attoparsec.Text as P
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as LBS
import Data.Char ( isDigit )
import qualified Data.Conduit.Binary as CB
import Data.Conduit.Lazy ( lazyConsume )
import qualified Data.Conduit.List as CL
import Data.Conduit.Process.Typed ( createSource )
import Data.Conduit.Zlib ( ungzip )
import Data.List.Split ( splitOn )
import qualified Data.Map as Map
import Data.Maybe ( fromJust )
import qualified Data.Set as Set
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Encoding as T
import qualified Data.Text.Lazy.Encoding as TL
import qualified Data.Text.Encoding.Error as T
import qualified Data.Yaml as Yaml
import Distribution.System ( Arch (..), OS, Platform (..) )
import qualified Distribution.System as Cabal
import Distribution.Text ( simpleParse )
import Distribution.Types.PackageName ( mkPackageName )
import Distribution.Version ( mkVersion )
import Network.HTTP.Client ( redirectCount )
import Network.HTTP.StackClient
( CheckHexDigest (..), HashCheck (..), getResponseBody
, getResponseStatusCode, httpLbs, httpJSON, mkDownloadRequest
, parseRequest, parseUrlThrow, setGitHubHeaders
, setHashChecks, setLengthCheck, setRequestMethod
, verifiedDownloadWithProgress, withResponse
)
import Network.HTTP.Simple ( getResponseHeader )
import Path
( (</>), addExtension, filename, fromAbsDir, parent
, parseAbsDir, parseAbsFile, parseRelDir, parseRelFile
, toFilePath
)
import Path.CheckInstall ( warnInstallSearchPathIssues )
import Path.Extended ( fileExtension )
import Path.Extra ( toFilePathNoTrailingSep )
import Path.IO
( canonicalizePath, doesFileExist, ensureDir, executable
, getPermissions, ignoringAbsence, listDir, removeDirRecur
, renameDir, renameFile, resolveFile', withTempDir
)
import RIO.List
( headMaybe, intercalate, intersperse, isPrefixOf
, maximumByMaybe, sort, sortOn, stripPrefix )
import RIO.Process
( EnvVars, HasProcessContext (..), ProcessContext
, augmentPath, augmentPathMap, doesExecutableExist, envVarsL
, exeSearchPathL, getStdout, mkProcessContext, modifyEnvVars
, proc, readProcess_, readProcessStdout, runProcess
, runProcess_, setStdout, waitExitCode, withModifyEnvVars
, withProcessWait, withWorkingDir, workingDirL
)
import Stack.Build.Haddock ( shouldHaddockDeps )
import Stack.Build.Source ( hashSourceMapData, loadSourceMap )
import Stack.Build.Target ( NeedTargets (..), parseTargets )
import Stack.Config.ConfigureScript ( ensureConfigureScript )
import Stack.Constants
( cabalPackageName, ghcBootScript,ghcConfigureMacOS
, ghcConfigurePosix, ghcConfigureWindows, hadrianScriptsPosix
, hadrianScriptsWindows, libDirs, osIsMacOS, osIsWindows
, relDirBin, relDirUsr, relFile7zdll, relFile7zexe
, relFileConfigure, relFileHadrianStackDotYaml
, relFileLibcMuslx86_64So1, relFileLibgmpSo10
, relFileLibgmpSo3, relFileLibncurseswSo6, relFileLibtinfoSo5
, relFileLibtinfoSo6, relFileMainHs, relFileStack
, relFileStackDotExe, relFileStackDotTmp
, relFileStackDotTmpDotExe, stackProgName, usrLibDirs
)
import Stack.Constants.Config ( distRelativeDir )
import Stack.GhcPkg
( createDatabase, getGlobalDB, ghcPkgPathEnvVar
, mkGhcPackagePath )
import Stack.Prelude
import Stack.Setup.Installed
( Tool (..), extraDirs, filterTools, getCompilerVersion
, installDir, listInstalled, markInstalled, tempInstallDir
, toolString, unmarkInstalled
)
import Stack.SourceMap
( actualFromGhc, globalsFromDump, pruneGlobals )
import Stack.Storage.User ( loadCompilerPaths, saveCompilerPaths )
import Stack.Types.Build.Exception ( BuildException (..) )
import Stack.Types.BuildConfig
( BuildConfig (..), HasBuildConfig (..), projectRootL
, wantedCompilerVersionL
)
import Stack.Types.BuildOpts ( BuildOptsCLI (..) )
import Stack.Types.Compiler
( ActualCompiler (..), CompilerException (..)
, CompilerRepository (..), WhichCompiler (..)
, compilerVersionText, getGhcVersion, isWantedCompiler
, wantedToActual, whichCompiler, whichCompilerL
)
import Stack.Types.CompilerBuild
( CompilerBuild (..), compilerBuildName, compilerBuildSuffix
)
import Stack.Types.CompilerPaths
( CompilerPaths (..), GhcPkgExe (..), HasCompiler (..) )
import Stack.Types.Config
( Config (..), HasConfig (..), envOverrideSettingsL
, ghcInstallHook
)
import Stack.Types.DownloadInfo ( DownloadInfo (..) )
import Stack.Types.DumpPackage ( DumpPackage (..) )
import Stack.Types.EnvConfig
( EnvConfig (..), HasEnvConfig (..), extraBinDirs
, packageDatabaseDeps, packageDatabaseExtra
, packageDatabaseLocal
)
import Stack.Types.EnvSettings ( EnvSettings (..), minimalEnvSettings )
import Stack.Types.ExtraDirs ( ExtraDirs (..) )
import Stack.Types.FileDigestCache ( newFileDigestCache )
import Stack.Types.GHCDownloadInfo ( GHCDownloadInfo (..) )
import Stack.Types.GHCVariant
( GHCVariant (..), HasGHCVariant (..), ghcVariantName
, ghcVariantSuffix
)
import Stack.Types.Platform
( HasPlatform (..), PlatformVariant (..)
, platformOnlyRelDir )
import Stack.Types.Runner ( HasRunner (..) )
import Stack.Types.SetupInfo ( SetupInfo (..) )
import Stack.Types.SourceMap ( SMActual (..), SourceMap (..) )
import Stack.Types.Version
( VersionCheck, stackMinorVersion, stackVersion )
import Stack.Types.VersionedDownloadInfo
( VersionedDownloadInfo (..) )
import qualified System.Directory as D
import System.Environment ( getExecutablePath, lookupEnv )
import System.IO.Error ( isPermissionError )
import System.FilePath ( searchPathSeparator, takeDrive )
import qualified System.FilePath as FP
import System.Permissions ( setFileExecutable )
import System.Uname ( getRelease )
-- | Type representing exceptions thrown by functions exported by the
-- "Stack.Setup" module
data SetupException
= WorkingDirectoryInvalidBug
| StackBinaryArchiveZipUnsupportedBug
deriving (Show, Typeable)
instance Exception SetupException where
displayException WorkingDirectoryInvalidBug = bugReport "[S-2076]"
"Invalid working directory."
displayException StackBinaryArchiveZipUnsupportedBug = bugReport "[S-3967]"
"FIXME: Handle zip files."
-- | Type representing \'pretty\' exceptions thrown by functions exported by the
-- "Stack.Setup" module
data SetupPrettyException
= GHCInstallFailed
!SomeException
!String
!String
![String]
!(Path Abs Dir)
!(Path Abs Dir)
!(Path Abs Dir)
| InvalidGhcAt !(Path Abs File) !SomeException
| ExecutableNotFound ![Path Abs File]
| SandboxedCompilerNotFound ![String] ![Path Abs Dir]
| UnsupportedSetupCombo !OS !Arch
| MissingDependencies ![String]
| UnknownCompilerVersion
!(Set.Set Text)
!WantedCompiler
!(Set.Set ActualCompiler)
| UnknownOSKey !Text
| GHCSanityCheckCompileFailed !SomeException !(Path Abs File)
| RequireCustomGHCVariant
| ProblemWhileDecompressing !(Path Abs File)
| SetupInfoMissingSevenz
| UnsupportedSetupConfiguration
| MSYS2NotFound !Text
| UnwantedCompilerVersion
| UnwantedArchitecture
| GHCInfoNotValidUTF8 !UnicodeException
| GHCInfoNotListOfPairs
| GHCInfoMissingGlobalPackageDB
| GHCInfoMissingTargetPlatform
| GHCInfoTargetPlatformInvalid !String
| CabalNotFound !(Path Abs File)
| GhcBootScriptNotFound
| HadrianScriptNotFound
| URLInvalid !String
| UnknownArchiveExtension !String
| Unsupported7z
| TarballInvalid !String
| TarballFileInvalid !String !(Path Abs File)
| UnknownArchiveStructure !(Path Abs File)
| StackReleaseInfoNotFound !String
| StackBinaryArchiveNotFound ![String]
| HadrianBindistNotFound
| DownloadAndInstallCompilerError
| StackBinaryArchiveUnsupported !Text
| StackBinaryNotInArchive !String !Text
| FileTypeInArchiveInvalid !Tar.Entry !Text
| BinaryUpgradeOnOSUnsupported !Cabal.OS
| BinaryUpgradeOnArchUnsupported !Cabal.Arch
| ExistingMSYS2NotDeleted !(Path Abs Dir) !IOException
deriving (Show, Typeable)
instance Pretty SetupPrettyException where
pretty (GHCInstallFailed ex step cmd args wd tempDir destDir) =
"[S-7441]"
<> line
<> string (displayException ex)
<> line
<> hang 2 ( fillSep
[ flow "Error encountered while"
, fromString step
, flow "GHC with"
]
<> line
<> style Shell (fromString (unwords (cmd : args)))
<> line
-- TODO: Figure out how to insert \ in the appropriate spots
-- hang 2 (shellColor (fillSep (fromString cmd : map fromString args))) <> line <>
<> fillSep
[ flow "run in"
, pretty wd
]
)
<> blankLine
<> flow "The following directories may now contain files, but won't be \
\used by Stack:"
<> line
<> bulletedList [pretty tempDir, pretty destDir]
<> blankLine
<> fillSep
[ flow "For more information consider rerunning with"
, style Shell "--verbose"
, "flag."
]
<> line
pretty (InvalidGhcAt compiler e) =
"[S-2476]"
<> line
<> fillSep
[ flow "Stack considers the compiler at"
, pretty compiler
, flow "to be invalid."
]
<> blankLine
<> flow "While assessing that compiler, Stack encountered the error:"
<> blankLine
<> ppException e
pretty (ExecutableNotFound toTry) =
"[S-4764]"
<> line
<> flow "Stack could not find any of the following executables:"
<> line
<> bulletedList (map pretty toTry)
pretty (SandboxedCompilerNotFound names fps) =
"[S-9953]"
<> line
<> fillSep
( ( flow "Stack could not find the sandboxed compiler. It looked for \
\one named one of:"
: mkNarrativeList Nothing False
( map fromString names :: [StyleDoc] )
)
<> ( flow "However, it could not find any on one of the paths:"
: mkNarrativeList Nothing False fps
)
)
<> blankLine
<> fillSep
[ flow "Perhaps a previously-installed compiler was not completely \
\uninstalled. For further information about uninstalling \
\tools, see the output of"
, style Shell (flow "stack uninstall") <> "."
]
pretty (UnsupportedSetupCombo os arch) =
"[S-1852]"
<> line
<> fillSep
[ flow "Stack does not know how to install GHC for the combination of \
\operating system"
, fromString $ show os
, "and architecture"
, fromString $ show arch <> "."
, flow "Please install manually."
]
pretty (MissingDependencies tools) =
"[S-2126]"
<> line
<> fillSep
( flow "The following executables are missing and must be installed:"
: mkNarrativeList Nothing False (map fromString tools :: [StyleDoc])
)
pretty (UnknownCompilerVersion oskeys wanted known) =
"[S-9443]"
<> line
<> fillSep
( ( flow "No setup information found for"
: style Current wanted'
: flow "on your platform. This probably means a GHC binary \
\distribution has not yet been added for OS key"
: mkNarrativeList (Just Shell) False
(map (fromString . T.unpack) (sort $ Set.toList oskeys) :: [StyleDoc])
)
<> ( flow "Supported versions:"
: mkNarrativeList Nothing False
( map
(fromString . T.unpack . compilerVersionText)
(sort $ Set.toList known)
:: [StyleDoc]
)
)
)
where
wanted' = fromString . T.unpack . utf8BuilderToText $ display wanted
pretty (UnknownOSKey oskey) =
"[S-6810]"
<> line
<> fillSep
[ flow "Unable to find installation URLs for OS key:"
, fromString $ T.unpack oskey <> "."
]
pretty (GHCSanityCheckCompileFailed e ghc) =
"[S-5159]"
<> line
<> fillSep
[ flow "The GHC located at"
, pretty ghc
, flow "failed to compile a sanity check. Please see:"
, style Url "http://docs.haskellstack.org/en/stable/install_and_upgrade/"
, flow "for more information. Stack encountered the following \
\error:"
]
<> blankLine
<> string (displayException e)
pretty RequireCustomGHCVariant =
"[S-8948]"
<> line
<> fillSep
[ flow "A custom"
, style Shell "--ghc-variant"
, flow "must be specified to use"
, style Shell "--ghc-bindist" <> "."
]
pretty (ProblemWhileDecompressing archive) =
"[S-2905]"
<> line
<> fillSep
[ flow "Problem while decompressing"
, pretty archive <> "."
]
pretty SetupInfoMissingSevenz =
"[S-9561]"
<> line
<> flow "SetupInfo missing Sevenz EXE/DLL."
pretty UnsupportedSetupConfiguration =
"[S-7748]"
<> line
<> flow "Stack does not know how to install GHC on your system \
\configuration. Please install manually."
pretty (MSYS2NotFound osKey) =
"[S-5308]"
<> line
<> fillSep
[ flow "MSYS2 not found for"
, fromString $ T.unpack osKey <> "."
]
pretty UnwantedCompilerVersion =
"[S-5127]"
<> line
<> flow "Not the compiler version we want."
pretty UnwantedArchitecture =
"[S-1540]"
<> line
<> flow "Not the architecture we want."
pretty (GHCInfoNotValidUTF8 e) =
"[S-8668]"
<> line
<> flow "GHC info is not valid UTF-8. Stack encountered the following \
\error:"
<> blankLine
<> string (displayException e)
pretty GHCInfoNotListOfPairs =
"[S-4878]"
<> line
<> flow "GHC info does not parse as a list of pairs."
pretty GHCInfoMissingGlobalPackageDB =
"[S-2965]"
<> line
<> flow "Key 'Global Package DB' not found in GHC info."
pretty GHCInfoMissingTargetPlatform =
"[S-5219]"
<> line
<> flow "Key 'Target platform' not found in GHC info."
pretty (GHCInfoTargetPlatformInvalid targetPlatform) =
"[S-8299]"
<> line
<> fillSep
[ flow "Invalid target platform in GHC info:"
, fromString targetPlatform <> "."
]
pretty (CabalNotFound compiler) =
"[S-2574]"
<> line
<> fillSep
[ flow "Cabal library not found in global package database for"
, pretty compiler <> "."
]
pretty GhcBootScriptNotFound =
"[S-8488]"
<> line
<> flow "No GHC boot script found."
pretty HadrianScriptNotFound =
"[S-1128]"
<> line
<> flow "No Hadrian build script found."
pretty (URLInvalid url) =
"[S-1906]"
<> line
<> fillSep
[ flow "`url` must be either an HTTP URL or a file path:"
, fromString url <> "."
]
pretty (UnknownArchiveExtension url) =
"[S-1648]"
<> line
<> fillSep
[ flow "Unknown extension for url:"
, style Url (fromString url) <> "."
]
pretty Unsupported7z =
"[S-4509]"
<> line
<> fillSep
[ flow "Stack does not know how to deal with"
, style File ".7z"
, flow "files on non-Windows operating systems."
]
pretty (TarballInvalid name) =
"[S-3158]"
<> line
<> fillSep
[ style File (fromString name)
, flow "must be a tarball file."
]
pretty (TarballFileInvalid name archiveFile) =
"[S-5252]"
<> line
<> fillSep
[ "Invalid"
, style File (fromString name)
, "filename:"
, pretty archiveFile <> "."
]
pretty (UnknownArchiveStructure archiveFile) =
"[S-1827]"
<> line
<> fillSep
[ flow "Expected a single directory within unpacked"
, pretty archiveFile <> "."
]
pretty (StackReleaseInfoNotFound url) =
"[S-9476]"
<> line
<> fillSep
[ flow "Could not get release information for Stack from:"
, style Url (fromString url) <> "."
]
pretty (StackBinaryArchiveNotFound platforms) =
"[S-4461]"
<> line
<> fillSep
( flow "Unable to find binary Stack archive for platforms:"
: mkNarrativeList Nothing False
(map fromString platforms :: [StyleDoc])
)
pretty HadrianBindistNotFound =
"[S-6617]"
<> line
<> flow "Can't find Hadrian-generated binary distribution."
pretty DownloadAndInstallCompilerError =
"[S-7227]"
<> line
<> flow "'downloadAndInstallCompiler' should not be reached with ghc-git."
pretty (StackBinaryArchiveUnsupported archiveURL) =
"[S-6636]"
<> line
<> fillSep
[ flow "Unknown archive format for Stack archive:"
, style Url (fromString $ T.unpack archiveURL) <> "."
]
pretty (StackBinaryNotInArchive exeName url) =
"[S-7871]"
<> line
<> fillSep
[ flow "Stack executable"
, style File (fromString exeName)
, flow "not found in archive from"
, style Url (fromString $ T.unpack url) <> "."
]
pretty (FileTypeInArchiveInvalid e url) =
"[S-5046]"
<> line
<> fillSep
[ flow "Invalid file type for tar entry named"
, fromString (Tar.entryPath e)
, flow "downloaded from"
, style Url (fromString $ T.unpack url) <> "."
]
pretty (BinaryUpgradeOnOSUnsupported os) =
"[S-4132]"
<> line
<> fillSep
[ flow "Binary upgrade not yet supported on OS:"
, fromString (show os) <> "."
]
pretty (BinaryUpgradeOnArchUnsupported arch) =
"[S-3249]"
<> line
<> fillSep
[ flow "Binary upgrade not yet supported on architecture:"
, fromString (show arch) <> "."
]
pretty (ExistingMSYS2NotDeleted destDir e) =
"[S-4230]"
<> line
<> fillSep
[ flow "Could not delete existing MSYS2 directory:"
, pretty destDir <> "."
, flow "Stack encountered the following error:"
]
<> blankLine
<> string (displayException e)
instance Exception SetupPrettyException
-- | Type representing exceptions thrown by 'performPathChecking'
data PerformPathCheckingException
= ProcessExited ExitCode String [String]
deriving (Show, Typeable)
instance Exception PerformPathCheckingException where
displayException (ProcessExited ec cmd args) = concat
[ "Error: [S-1991]\n"
, "Process exited with "
, displayException ec
, ": "
, unwords (cmd:args)
]
-- | Default location of the stack-setup.yaml file
defaultSetupInfoYaml :: String
defaultSetupInfoYaml =
"https://raw.githubusercontent.com/commercialhaskell/stackage-content/master/stack/stack-setup-2.yaml"
data SetupOpts = SetupOpts
{ soptsInstallIfMissing :: !Bool
, soptsUseSystem :: !Bool
-- ^ Should we use a system compiler installation, if available?
, soptsWantedCompiler :: !WantedCompiler
, soptsCompilerCheck :: !VersionCheck
, soptsStackYaml :: !(Maybe (Path Abs File))
-- ^ If we got the desired GHC version from that file
, soptsForceReinstall :: !Bool
, soptsSanityCheck :: !Bool
-- ^ Run a sanity check on the selected GHC
, soptsSkipGhcCheck :: !Bool
-- ^ Don't check for a compatible GHC version/architecture
, soptsSkipMsys :: !Bool
-- ^ Do not use a custom msys installation on Windows
, soptsResolveMissingGHC :: !(Maybe Text)
-- ^ Message shown to user for how to resolve the missing GHC
, soptsGHCBindistURL :: !(Maybe String)
-- ^ Alternate GHC binary distribution (requires custom GHCVariant)
}
deriving Show
-- | Modify the environment variables (like PATH) appropriately, possibly doing
-- installation too
setupEnv ::
NeedTargets
-> BuildOptsCLI
-> Maybe Text -- ^ Message to give user when necessary GHC is not available
-> RIO BuildConfig EnvConfig
setupEnv needTargets boptsCLI mResolveMissingGHC = do
config <- view configL
bc <- view buildConfigL
let stackYaml = bcStackYaml bc
platform <- view platformL
wcVersion <- view wantedCompilerVersionL
wanted <- view wantedCompilerVersionL
actual <- either throwIO pure $ wantedToActual wanted
let wc = actual^.whichCompilerL
let sopts = SetupOpts
{ soptsInstallIfMissing = configInstallGHC config
, soptsUseSystem = configSystemGHC config
, soptsWantedCompiler = wcVersion
, soptsCompilerCheck = configCompilerCheck config
, soptsStackYaml = Just stackYaml
, soptsForceReinstall = False
, soptsSanityCheck = False
, soptsSkipGhcCheck = configSkipGHCCheck config
, soptsSkipMsys = configSkipMsys config
, soptsResolveMissingGHC = mResolveMissingGHC
, soptsGHCBindistURL = Nothing
}
(compilerPaths, ghcBin) <- ensureCompilerAndMsys sopts
let compilerVer = cpCompilerVersion compilerPaths
-- Modify the initial environment to include the GHC path, if a local GHC
-- is being used
menv0 <- view processContextL
env <- either throwM (pure . removeHaskellEnvVars)
$ augmentPathMap
(map toFilePath $ edBins ghcBin)
(view envVarsL menv0)
menv <- mkProcessContext env
logDebug "Resolving package entries"
(sourceMap, sourceMapHash) <- runWithGHC menv compilerPaths $ do
smActual <- actualFromGhc (bcSMWanted bc) compilerVer
let actualPkgs = Map.keysSet (smaDeps smActual) <>
Map.keysSet (smaProject smActual)
prunedActual = smActual
{ smaGlobal = pruneGlobals (smaGlobal smActual) actualPkgs }
haddockDeps = shouldHaddockDeps (configBuild config)
targets <- parseTargets needTargets haddockDeps boptsCLI prunedActual
sourceMap <- loadSourceMap targets boptsCLI smActual
sourceMapHash <- hashSourceMapData boptsCLI sourceMap
pure (sourceMap, sourceMapHash)
fileDigestCache <- newFileDigestCache
let envConfig0 = EnvConfig
{ envConfigBuildConfig = bc
, envConfigBuildOptsCLI = boptsCLI
, envConfigFileDigestCache = fileDigestCache
, envConfigSourceMap = sourceMap
, envConfigSourceMapHash = sourceMapHash
, envConfigCompilerPaths = compilerPaths
}
-- extra installation bin directories
mkDirs <- runRIO envConfig0 extraBinDirs
let mpath = Map.lookup "PATH" env
depsPath <-
either throwM pure $ augmentPath (toFilePath <$> mkDirs False) mpath
localsPath <-
either throwM pure $ augmentPath (toFilePath <$> mkDirs True) mpath
deps <- runRIO envConfig0 packageDatabaseDeps
runWithGHC menv compilerPaths $ createDatabase (cpPkg compilerPaths) deps
localdb <- runRIO envConfig0 packageDatabaseLocal
runWithGHC menv compilerPaths $ createDatabase (cpPkg compilerPaths) localdb
extras <- runReaderT packageDatabaseExtra envConfig0
let mkGPP locals =
mkGhcPackagePath locals localdb deps extras $ cpGlobalDB compilerPaths
distDir <- runReaderT distRelativeDir envConfig0 >>= canonicalizePath
executablePath <- liftIO getExecutablePath
utf8EnvVars <- withProcessContext menv $ getUtf8EnvVars compilerVer
mGhcRtsEnvVar <- liftIO $ lookupEnv "GHCRTS"
envRef <- liftIO $ newIORef Map.empty
let getProcessContext' es = do
m <- readIORef envRef
case Map.lookup es m of
Just eo -> pure eo
Nothing -> do
eo <- mkProcessContext
$ Map.insert
"PATH"
(if esIncludeLocals es then localsPath else depsPath)
$ (if esIncludeGhcPackagePath es
then
Map.insert
(ghcPkgPathEnvVar wc)
(mkGPP (esIncludeLocals es))
else id)
$ (if esStackExe es
then Map.insert "STACK_EXE" (T.pack executablePath)
else id)
$ (if esLocaleUtf8 es
then Map.union utf8EnvVars
else id)
$ case (soptsSkipMsys sopts, platform) of
(False, Platform Cabal.I386 Cabal.Windows) ->
Map.insert "MSYSTEM" "MINGW32"
(False, Platform Cabal.X86_64 Cabal.Windows) ->
Map.insert "MSYSTEM" "MINGW64"
_ -> id
-- See https://github.com/commercialhaskell/stack/issues/3444
$ case (esKeepGhcRts es, mGhcRtsEnvVar) of
(True, Just ghcRts) -> Map.insert "GHCRTS" (T.pack ghcRts)
_ -> id
-- For reasoning and duplication, see:
-- https://github.com/commercialhaskell/stack/issues/70
$ Map.insert
"HASKELL_PACKAGE_SANDBOX"
(T.pack $ toFilePathNoTrailingSep deps)
$ Map.insert "HASKELL_PACKAGE_SANDBOXES"
(T.pack $ if esIncludeLocals es
then intercalate [searchPathSeparator]
[ toFilePathNoTrailingSep localdb
, toFilePathNoTrailingSep deps
, ""
]
else intercalate [searchPathSeparator]
[ toFilePathNoTrailingSep deps
, ""
])
$ Map.insert
"HASKELL_DIST_DIR"
(T.pack $ toFilePathNoTrailingSep distDir)
-- Make sure that any .ghc.environment files
-- are ignored, since we're setting up our
-- own package databases. See
-- https://github.com/commercialhaskell/stack/issues/4706
$ (case cpCompilerVersion compilerPaths of
ACGhc version | version >= mkVersion [8, 4, 4] ->
Map.insert "GHC_ENVIRONMENT" "-"
_ -> id)
env
() <- atomicModifyIORef envRef $ \m' ->
(Map.insert es eo m', ())
pure eo
envOverride <- liftIO $ getProcessContext' minimalEnvSettings
pure EnvConfig
{ envConfigBuildConfig = bc
{ bcConfig = addIncludeLib ghcBin
$ set processContextL envOverride
(view configL bc)
{ configProcessContextSettings = getProcessContext'
}
}
, envConfigBuildOptsCLI = boptsCLI
, envConfigFileDigestCache = fileDigestCache
, envConfigSourceMap = sourceMap
, envConfigSourceMapHash = sourceMapHash
, envConfigCompilerPaths = compilerPaths
}
-- | A modified env which we know has an installed compiler on the PATH.
data WithGHC env = WithGHC !CompilerPaths !env
insideL :: Lens' (WithGHC env) env
insideL = lens (\(WithGHC _ x) -> x) (\(WithGHC cp _) -> WithGHC cp)
instance HasLogFunc env => HasLogFunc (WithGHC env) where
logFuncL = insideL.logFuncL
instance HasRunner env => HasRunner (WithGHC env) where
runnerL = insideL.runnerL
instance HasProcessContext env => HasProcessContext (WithGHC env) where
processContextL = insideL.processContextL
instance HasStylesUpdate env => HasStylesUpdate (WithGHC env) where
stylesUpdateL = insideL.stylesUpdateL
instance HasTerm env => HasTerm (WithGHC env) where
useColorL = insideL.useColorL
termWidthL = insideL.termWidthL
instance HasPantryConfig env => HasPantryConfig (WithGHC env) where
pantryConfigL = insideL.pantryConfigL
instance HasConfig env => HasPlatform (WithGHC env) where
platformL = configL.platformL
{-# INLINE platformL #-}
platformVariantL = configL.platformVariantL
{-# INLINE platformVariantL #-}
instance HasConfig env => HasGHCVariant (WithGHC env) where
ghcVariantL = configL.ghcVariantL
{-# INLINE ghcVariantL #-}
instance HasConfig env => HasConfig (WithGHC env) where
configL = insideL.configL
instance HasBuildConfig env => HasBuildConfig (WithGHC env) where
buildConfigL = insideL.buildConfigL
instance HasCompiler (WithGHC env) where
compilerPathsL = to (\(WithGHC cp _) -> cp)
-- | Set up a modified environment which includes the modified PATH that GHC can
-- be found on. This is needed for looking up global package information and ghc
-- fingerprint (result from 'ghc --info').
runWithGHC ::
HasConfig env
=> ProcessContext
-> CompilerPaths
-> RIO (WithGHC env) a
-> RIO env a
runWithGHC pc cp inner = do
env <- ask
let envg
= WithGHC cp $
set envOverrideSettingsL (\_ -> pure pc) $
set processContextL pc env
runRIO envg inner
-- | A modified environment which we know has MSYS2 on the PATH.
newtype WithMSYS env = WithMSYS env
insideMSYSL :: Lens' (WithMSYS env) env
insideMSYSL = lens (\(WithMSYS x) -> x) (\(WithMSYS _) -> WithMSYS)
instance HasLogFunc env => HasLogFunc (WithMSYS env) where
logFuncL = insideMSYSL.logFuncL
instance HasRunner env => HasRunner (WithMSYS env) where
runnerL = insideMSYSL.runnerL
instance HasProcessContext env => HasProcessContext (WithMSYS env) where
processContextL = insideMSYSL.processContextL
instance HasStylesUpdate env => HasStylesUpdate (WithMSYS env) where
stylesUpdateL = insideMSYSL.stylesUpdateL
instance HasTerm env => HasTerm (WithMSYS env) where
useColorL = insideMSYSL.useColorL
termWidthL = insideMSYSL.termWidthL
instance HasPantryConfig env => HasPantryConfig (WithMSYS env) where
pantryConfigL = insideMSYSL.pantryConfigL
instance HasConfig env => HasPlatform (WithMSYS env) where
platformL = configL.platformL
{-# INLINE platformL #-}
platformVariantL = configL.platformVariantL
{-# INLINE platformVariantL #-}
instance HasConfig env => HasGHCVariant (WithMSYS env) where
ghcVariantL = configL.ghcVariantL
{-# INLINE ghcVariantL #-}
instance HasConfig env => HasConfig (WithMSYS env) where
configL = insideMSYSL.configL
instance HasBuildConfig env => HasBuildConfig (WithMSYS env) where
buildConfigL = insideMSYSL.buildConfigL
-- | Set up a modified environment which includes the modified PATH that MSYS2
-- can be found on.
runWithMSYS ::
HasConfig env
=> Maybe ExtraDirs
-> RIO (WithMSYS env) a
-> RIO env a
runWithMSYS mmsysPaths inner = do
env <- ask
pc0 <- view processContextL
pc <- case mmsysPaths of
Nothing -> pure pc0
Just msysPaths -> do
envars <- either throwM pure $
augmentPathMap
(map toFilePath $ edBins msysPaths)
(view envVarsL pc0)
mkProcessContext envars
let envMsys
= WithMSYS $
set envOverrideSettingsL (\_ -> pure pc) $
set processContextL pc env
runRIO envMsys inner
-- | special helper for GHCJS which needs an updated source map
-- only project dependencies should get included otherwise source map hash will
-- get changed and EnvConfig will become inconsistent
rebuildEnv ::
EnvConfig
-> NeedTargets
-> Bool
-> BuildOptsCLI
-> RIO env EnvConfig
rebuildEnv envConfig needTargets haddockDeps boptsCLI = do
let bc = envConfigBuildConfig envConfig
cp = envConfigCompilerPaths envConfig
compilerVer = smCompiler $ envConfigSourceMap envConfig
runRIO (WithGHC cp bc) $ do
smActual <- actualFromGhc (bcSMWanted bc) compilerVer
let actualPkgs =
Map.keysSet (smaDeps smActual) <> Map.keysSet (smaProject smActual)
prunedActual = smActual
{ smaGlobal = pruneGlobals (smaGlobal smActual) actualPkgs }
targets <- parseTargets needTargets haddockDeps boptsCLI prunedActual
sourceMap <- loadSourceMap targets boptsCLI smActual
pure $ envConfig
{ envConfigSourceMap = sourceMap
, envConfigBuildOptsCLI = boptsCLI
}
-- | Some commands (script, ghci and exec) set targets dynamically
-- see also the note about only local targets for rebuildEnv
withNewLocalBuildTargets ::
HasEnvConfig env
=> [Text]
-> RIO env a
-> RIO env a
withNewLocalBuildTargets targets f = do
envConfig <- view envConfigL
haddockDeps <- view $ configL.to configBuild.to shouldHaddockDeps
let boptsCLI = envConfigBuildOptsCLI envConfig
envConfig' <- rebuildEnv envConfig NeedTargets haddockDeps $
boptsCLI {boptsCLITargets = targets}
local (set envConfigL envConfig') f
-- | Add the include and lib paths to the given Config
addIncludeLib :: ExtraDirs -> Config -> Config
addIncludeLib (ExtraDirs _bins includes libs) config = config
{ configExtraIncludeDirs =
configExtraIncludeDirs config ++
map toFilePathNoTrailingSep includes
, configExtraLibDirs =
configExtraLibDirs config ++
map toFilePathNoTrailingSep libs
}
-- | Ensure both the compiler and the msys toolchain are installed and
-- provide the PATHs to add if necessary
ensureCompilerAndMsys ::
(HasBuildConfig env, HasGHCVariant env)
=> SetupOpts
-> RIO env (CompilerPaths, ExtraDirs)
ensureCompilerAndMsys sopts = do
getSetupInfo' <- memoizeRef getSetupInfo
mmsys2Tool <- ensureMsys sopts getSetupInfo'
mmsysPaths <- maybe (pure Nothing) (fmap Just . extraDirs) mmsys2Tool
actual <- either throwIO pure $ wantedToActual $ soptsWantedCompiler sopts
didWarn <- warnUnsupportedCompiler $ getGhcVersion actual
-- Modify the initial environment to include the MSYS2 path, if MSYS2 is being
-- used
(cp, ghcPaths) <- runWithMSYS mmsysPaths $ ensureCompiler sopts getSetupInfo'
warnUnsupportedCompilerCabal cp didWarn
let paths = maybe ghcPaths (ghcPaths <>) mmsysPaths
pure (cp, paths)
-- | See <https://github.com/commercialhaskell/stack/issues/4246>
warnUnsupportedCompiler :: HasTerm env => Version -> RIO env Bool
warnUnsupportedCompiler ghcVersion =
if
| ghcVersion < mkVersion [7, 8] -> do
prettyWarnL
[ flow "Stack will almost certainly fail with GHC below version 7.8, \