-
Notifications
You must be signed in to change notification settings - Fork 841
/
Setup.hs
2141 lines (2012 loc) · 95.3 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 ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-} -- ghc < 7.10
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE TemplateHaskell #-}
module Stack.Setup
( setupEnv
, ensureCompiler
, ensureDockerStackExe
, getSystemCompiler
, getCabalInstallVersion
, SetupOpts (..)
, defaultSetupInfoYaml
, removeHaskellEnvVars
, withNewLocalBuildTargets
-- * Stack binary download
, StackReleaseInfo
, getDownloadVersion
, stackVersion
, preferredPlatforms
, downloadStackReleaseInfo
, downloadStackExe
) where
import qualified Codec.Archive.Tar as Tar
import Control.Applicative (empty)
import Control.Monad.State (get, put, modify)
import "cryptonite" Crypto.Hash (SHA1(..), SHA256(..))
import Data.Aeson.Extended
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.Lazy.Char8 as BL8
import Data.Char (isSpace)
import Data.Conduit (await, yield, awaitForever)
import qualified Data.Conduit.Binary as CB
import Data.Conduit.Lazy (lazyConsume)
import Data.Conduit.Lift (evalStateC)
import qualified Data.Conduit.List as CL
import Data.Conduit.Process.Typed (eceStderr)
import Data.Conduit.Zlib (ungzip)
import Data.Foldable (maximumBy)
import qualified Data.HashMap.Strict as HashMap
import Data.List hiding (concat, elem, maximumBy, any)
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Encoding.Error as T
import Data.Time.Clock (NominalDiffTime, diffUTCTime, getCurrentTime)
import qualified Data.Yaml as Yaml
import Distribution.System (OS, Arch (..), Platform (..))
import qualified Distribution.System as Cabal
import Distribution.Text (simpleParse)
import Distribution.Types.PackageName (mkPackageName, unPackageName)
import Distribution.Version (mkVersion)
import Lens.Micro (set)
import Network.HTTP.StackClient (CheckHexDigest (..), DownloadRequest (..), HashCheck (..),
drRetryPolicyDefault, getResponseBody, getResponseStatusCode,
httpLbs, httpJSON, parseRequest, parseUrlThrow, setGithubHeaders,
verifiedDownload, withResponse)
import Path
import Path.CheckInstall (warnInstallSearchPathIssues)
import Path.Extra (toFilePathNoTrailingSep)
import Path.IO hiding (findExecutable, withSystemTempDir)
import Prelude (until)
import qualified RIO
import RIO.List
import RIO.PrettyPrint
import RIO.Process
import Stack.Build (build)
import Stack.Build.Haddock (shouldHaddockDeps)
import Stack.Build.Source (loadSourceMap)
import Stack.Build.Target (NeedTargets(..), parseTargets)
import Stack.Config (loadConfig)
import Stack.Constants
import Stack.Constants.Config (distRelativeDir)
import Stack.GhcPkg (createDatabase, getCabalPkgVer, getGlobalDB, mkGhcPackagePath, ghcPkgPathEnvVar)
import Stack.PackageDump (DumpPackage (..))
import Stack.Prelude hiding (Display (..))
import Stack.SourceMap
import Stack.Setup.Installed
import Stack.Types.Build
import Stack.Types.Compiler
import Stack.Types.CompilerBuild
import Stack.Types.Config
import Stack.Types.Docker
import Stack.Types.GhcPkgId (parseGhcPkgId)
import Stack.Types.Runner
import Stack.Types.SourceMap
import Stack.Types.Version
import qualified System.Directory as D
import System.Environment (getExecutablePath, lookupEnv)
import System.Exit (ExitCode (..), exitFailure)
import System.IO.Error (isPermissionError)
import System.FilePath (searchPathSeparator)
import qualified System.FilePath as FP
import System.Permissions (setFileExecutable)
import Text.Printf (printf)
#if !WINDOWS
import System.Uname (uname, release)
import Data.List.Split (splitOn)
import Foreign.C (throwErrnoIfMinus1_, peekCString)
import Foreign.Marshal (alloca)
#endif
-- | Default location of the stack-setup.yaml file
defaultSetupInfoYaml :: String
defaultSetupInfoYaml =
"https://raw.githubusercontent.com/fpco/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
, soptsUpgradeCabal :: !(Maybe UpgradeTo)
-- ^ Upgrade the global Cabal library in the database to the newest
-- version. Only works reliably with a stack-managed installation.
, soptsResolveMissingGHC :: !(Maybe Text)
-- ^ Message shown to user for how to resolve the missing GHC
, soptsSetupInfoYaml :: !FilePath
-- ^ Location of the main stack-setup.yaml file
, soptsGHCBindistURL :: !(Maybe String)
-- ^ Alternate GHC binary distribution (requires custom GHCVariant)
, soptsGHCJSBootOpts :: [String]
-- ^ Additional ghcjs-boot options, the default is "--clean"
}
deriving Show
data SetupException = UnsupportedSetupCombo OS Arch
| MissingDependencies [String]
| UnknownCompilerVersion (Set.Set Text) WantedCompiler (Set.Set ActualCompiler)
| UnknownOSKey Text
| GHCSanityCheckCompileFailed SomeException (Path Abs File)
| WantedMustBeGHC
| RequireCustomGHCVariant
| ProblemWhileDecompressing (Path Abs File)
| SetupInfoMissingSevenz
| GHCJSRequiresStandardVariant
| GHCJSNotBooted
| DockerStackExeNotFound Version Text
| UnsupportedSetupConfiguration
deriving Typeable
instance Exception SetupException
instance Show SetupException where
show (UnsupportedSetupCombo os arch) = concat
[ "I don't know how to install GHC for "
, show (os, arch)
, ", please install manually"
]
show (MissingDependencies tools) =
"The following executables are missing and must be installed: " ++
intercalate ", " tools
show (UnknownCompilerVersion oskeys wanted known) = concat
[ "No setup information found for "
, T.unpack $ utf8BuilderToText $ RIO.display wanted
, " on your platform.\nThis probably means a GHC bindist has not yet been added for OS key '"
, T.unpack (T.intercalate "', '" (sort $ Set.toList oskeys))
, "'.\nSupported versions: "
, T.unpack (T.intercalate ", " (map compilerVersionText (sort $ Set.toList known)))
]
show (UnknownOSKey oskey) =
"Unable to find installation URLs for OS key: " ++
T.unpack oskey
show (GHCSanityCheckCompileFailed e ghc) = concat
[ "The GHC located at "
, toFilePath ghc
, " failed to compile a sanity check. Please see:\n\n"
, " http://docs.haskellstack.org/en/stable/install_and_upgrade/\n\n"
, "for more information. Exception was:\n"
, show e
]
show WantedMustBeGHC =
"The wanted compiler must be GHC"
show RequireCustomGHCVariant =
"A custom --ghc-variant must be specified to use --ghc-bindist"
show (ProblemWhileDecompressing archive) =
"Problem while decompressing " ++ toFilePath archive
show SetupInfoMissingSevenz =
"SetupInfo missing Sevenz EXE/DLL"
show GHCJSRequiresStandardVariant =
"stack does not yet support using --ghc-variant with GHCJS"
show GHCJSNotBooted =
"GHCJS does not yet have its boot packages installed. Use \"stack setup\" to attempt to run ghcjs-boot."
show (DockerStackExeNotFound stackVersion' osKey) = concat
[ stackProgName
, "-"
, versionString stackVersion'
, " executable not found for "
, T.unpack osKey
, "\nUse the '"
, T.unpack dockerStackExeArgName
, "' option to specify a location"]
show UnsupportedSetupConfiguration =
"I don't know how to install GHC on your system configuration, please install manually"
-- | Modify the environment variables (like PATH) appropriately, possibly doing installation too
setupEnv :: (HasBuildConfig env, HasGHCVariant env)
=> NeedTargets
-> BuildOptsCLI
-> Maybe Text -- ^ Message to give user when necessary GHC is not available
-> RIO env EnvConfig
setupEnv needTargets boptsCLI mResolveMissingGHC = do
config <- view configL
bc <- view buildConfigL
let stackYaml = bcStackYaml bc
platform <- view platformL
wcVersion <- view wantedCompilerVersionL
wc <- view $ wantedCompilerVersionL.to wantedToActual.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
, soptsUpgradeCabal = Nothing
, soptsResolveMissingGHC = mResolveMissingGHC
, soptsSetupInfoYaml = defaultSetupInfoYaml
, soptsGHCBindistURL = Nothing
, soptsGHCJSBootOpts = ["--clean"]
}
(mghcBin, mCompilerBuild, _) <-
case bcDownloadCompiler bc of
SkipDownloadCompiler -> return (Nothing, Nothing, False)
WithDownloadCompiler -> ensureCompiler sopts
-- Modify the initial environment to include the GHC path, if a local GHC
-- is being used
menv0 <- view processContextL
env <- either throwM (return . removeHaskellEnvVars)
$ augmentPathMap
(map toFilePath $ maybe [] edBins mghcBin)
(view envVarsL menv0)
menv <- mkProcessContext env
-- FIXME currently this fails with SkipDownloadcompiler
(compilerVer, cabalVer, globaldb) <- withProcessContext menv $ runConcurrently $ (,,)
<$> Concurrently (getCompilerVersion wc)
<*> Concurrently (getCabalPkgVer wc)
<*> Concurrently (getGlobalDB wc)
logDebug "Resolving package entries"
-- 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').
let bcPath :: BuildConfig
bcPath = set envOverrideSettingsL (\_ -> return menv) $
set processContextL menv bc
sourceMap <- runRIO bcPath $ do
(smActual, prunedActual) <- case bcDownloadCompiler bc of
SkipDownloadCompiler -> do
-- FIXME temprorary version, should be resolved the same way as getCompilerVersion above
sma <- actualFromHints (bcSMWanted bc) compilerVer
let noDepsDump :: PackageName -> a -> DumpedGlobalPackage
noDepsDump pname _ = DumpPackage
{ dpGhcPkgId = fromMaybe (error "bad package name") $
parseGhcPkgId (T.pack $ unPackageName pname)
, dpPackageIdent = PackageIdentifier pname (mkVersion [])
, dpParentLibIdent = Nothing
, dpLicense = Nothing
, dpLibDirs = []
, dpLibraries = []
, dpHasExposedModules = True
, dpExposedModules = mempty
, dpDepends = []
, dpHaddockInterfaces = []
, dpHaddockHtml = Nothing
, dpProfiling = ()
, dpHaddock = ()
, dpSymbols = ()
, dpIsExposed = True
}
fakeDump = sma {
smaGlobal = Map.mapWithKey noDepsDump (smaGlobal sma)
}
fakePruned = sma {
smaGlobal = Map.map (\(GlobalPackageVersion v) -> GlobalPackage v)
(smaGlobal sma)
}
return (fakeDump, fakePruned)
WithDownloadCompiler -> do
sma <- actualFromGhc (bcSMWanted bc) compilerVer
let actualPkgs = Map.keysSet (smaDeps sma) <>
Map.keysSet (smaProject sma)
return ( sma
, sma {
smaGlobal = pruneGlobals (smaGlobal sma) actualPkgs
}
)
let haddockDeps = shouldHaddockDeps (configBuild config)
targets <- parseTargets needTargets haddockDeps boptsCLI prunedActual
loadSourceMap targets boptsCLI smActual
let envConfig0 = EnvConfig
{ envConfigBuildConfig = bc
, envConfigCabalVersion = cabalVer
, envConfigBuildOptsCLI = boptsCLI
, envConfigSourceMap = sourceMap
, envConfigCompilerBuild = mCompilerBuild
}
-- extra installation bin directories
mkDirs <- runRIO envConfig0 extraBinDirs
let mpath = Map.lookup "PATH" env
depsPath <- either throwM return $ augmentPath (toFilePath <$> mkDirs False) mpath
localsPath <- either throwM return $ augmentPath (toFilePath <$> mkDirs True) mpath
deps <- runRIO envConfig0 packageDatabaseDeps
withProcessContext menv $ createDatabase wc deps
localdb <- runRIO envConfig0 packageDatabaseLocal
withProcessContext menv $ createDatabase wc localdb
extras <- runReaderT packageDatabaseExtra envConfig0
let mkGPP locals = mkGhcPackagePath locals localdb deps extras globaldb
distDir <- runReaderT distRelativeDir envConfig0
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 -> return 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/fpco/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) env
() <- atomicModifyIORef envRef $ \m' ->
(Map.insert es eo m', ())
return eo
envOverride <- liftIO $ getProcessContext' minimalEnvSettings
return EnvConfig
{ envConfigBuildConfig = bc
{ bcConfig = maybe id addIncludeLib mghcBin
$ set processContextL envOverride
(view configL bc)
{ configProcessContextSettings = getProcessContext'
}
}
, envConfigCabalVersion = cabalVer
, envConfigBuildOptsCLI = boptsCLI
, envConfigSourceMap = sourceMap
, envConfigCompilerBuild = mCompilerBuild
}
-- | 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
compilerVer = smCompiler $ envConfigSourceMap envConfig
runRIO 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
return $
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 = Set.union
(configExtraIncludeDirs config)
(Set.fromList (map toFilePathNoTrailingSep includes))
, configExtraLibDirs = Set.union
(configExtraLibDirs config)
(Set.fromList (map toFilePathNoTrailingSep libs))
}
-- | Ensure compiler (ghc or ghcjs) is installed and provide the PATHs to add if necessary
ensureCompiler :: (HasConfig env, HasGHCVariant env)
=> SetupOpts
-> RIO env (Maybe ExtraDirs, Maybe CompilerBuild, Bool)
ensureCompiler sopts = do
let wc = whichCompiler (wantedToActual (soptsWantedCompiler sopts))
when (getGhcVersion (wantedToActual (soptsWantedCompiler sopts)) < mkVersion [7, 8]) $ do
logWarn "Stack will almost certainly fail with GHC below version 7.8"
logWarn "Valiantly attempting to run anyway, but I know this is doomed"
logWarn "For more information, see: https://github.com/commercialhaskell/stack/issues/648"
logWarn ""
msystem <-
if soptsUseSystem sopts
then do
logDebug "Getting system compiler version"
getSystemCompiler wc
else return Nothing
Platform expectedArch _ <- view platformL
let canUseCompiler compilerVersion arch
| soptsSkipGhcCheck sopts = True
| otherwise = isWanted compilerVersion && arch == expectedArch
isWanted = isWantedCompiler (soptsCompilerCheck sopts) (soptsWantedCompiler sopts)
needLocal = not (any (uncurry canUseCompiler) msystem)
getSetupInfo' <- memoizeRef (getSetupInfo (soptsSetupInfoYaml sopts))
let getMmsys2Tool = do
platform <- view platformL
localPrograms <- view $ configL.to configLocalPrograms
installed <- listInstalled localPrograms
case platform of
Platform _ Cabal.Windows | not (soptsSkipMsys sopts) ->
case getInstalledTool installed (mkPackageName "msys2") (const True) of
Just tool -> return (Just tool)
Nothing
| soptsInstallIfMissing sopts -> do
si <- runMemoized getSetupInfo'
osKey <- getOSKey platform
config <- view configL
VersionedDownloadInfo version info <-
case Map.lookup osKey $ siMsys2 si of
Just x -> return x
Nothing -> throwString $ "MSYS2 not found for " ++ T.unpack osKey
let tool = Tool (PackageIdentifier (mkPackageName "msys2") version)
Just <$> downloadAndInstallTool (configLocalPrograms config) si info tool (installMsys2Windows osKey)
| otherwise -> do
logWarn "Continuing despite missing tool: msys2"
return Nothing
_ -> return Nothing
-- If we need to install a GHC or MSYS, try to do so
-- Return the additional directory paths of GHC & MSYS.
(mtools, compilerBuild) <- if needLocal
then do
-- Install GHC
ghcVariant <- view ghcVariantL
config <- view configL
let localPrograms = configLocalPrograms config
installed <- listInstalled localPrograms
possibleCompilers <-
case wc of
Ghc -> do
ghcBuilds <- getGhcBuilds
forM ghcBuilds $ \ghcBuild -> do
ghcPkgName <- parsePackageNameThrowing ("ghc" ++ ghcVariantSuffix ghcVariant ++ compilerBuildSuffix ghcBuild)
return (getInstalledTool installed ghcPkgName (isWanted . ACGhc), ghcBuild)
Ghcjs -> return [(getInstalledGhcjs installed isWanted, CompilerBuildStandard)]
let existingCompilers = concatMap
(\(installedCompiler, compilerBuild) ->
case (installedCompiler, soptsForceReinstall sopts) of
(Just tool, False) -> [(tool, compilerBuild)]
_ -> [])
possibleCompilers
logDebug $
"Found already installed GHC builds: " <>
mconcat (intersperse ", " (map (fromString . compilerBuildName . snd) existingCompilers))
(compilerTool, compilerBuild) <- case existingCompilers of
(tool, build_):_ -> return (tool, build_)
[]
| soptsInstallIfMissing sopts -> do
si <- runMemoized getSetupInfo'
downloadAndInstallPossibleCompilers
(map snd possibleCompilers)
si
(soptsWantedCompiler sopts)
(soptsCompilerCheck sopts)
(soptsGHCBindistURL sopts)
| otherwise -> do
recommendSystemGhc <-
if soptsUseSystem sopts
then return False
else do
msystemGhc <- getSystemCompiler wc
return (any (uncurry canUseCompiler) msystemGhc)
let suggestion = fromMaybe
(mconcat
([ "To install the correct GHC into "
, T.pack (toFilePath (configLocalPrograms config))
, ", try running \"stack setup\" or use the \"--install-ghc\" flag."
] ++
[ " To use your system GHC installation, run \"stack config set system-ghc --global true\", or use the \"--system-ghc\" flag."
| recommendSystemGhc
]))
(soptsResolveMissingGHC sopts)
throwM $ CompilerVersionMismatch
msystem
(soptsWantedCompiler sopts, expectedArch)
ghcVariant
(case possibleCompilers of
[] -> CompilerBuildStandard
(_, compilerBuild):_ -> compilerBuild)
(soptsCompilerCheck sopts)
(soptsStackYaml sopts)
suggestion
-- Install msys2 on windows, if necessary
mmsys2Tool <- getMmsys2Tool
return (Just (Just compilerTool, mmsys2Tool), compilerBuild)
-- Have the right ghc, may still need msys
else do
mmsys2Tool <- getMmsys2Tool
return (Just (Nothing, mmsys2Tool), CompilerBuildStandard)
mpaths <- case mtools of
Nothing -> return Nothing
Just (compilerTool, mmsys2Tool) -> do
-- Add GHC's and MSYS's paths to the config.
let idents = catMaybes [compilerTool, mmsys2Tool]
paths <- mapM extraDirs idents
return $ Just $ mconcat paths
menv <-
case mpaths of
Nothing -> view processContextL
Just ed -> do
menv0 <- view processContextL
m <- either throwM return
$ augmentPathMap (toFilePath <$> edBins ed) (view envVarsL menv0)
mkProcessContext (removeHaskellEnvVars m)
forM_ (soptsUpgradeCabal sopts) $ \version -> do
unless needLocal $ do
logWarn "Trying to change a Cabal library on a GHC not installed by stack."
logWarn "This may fail, caveat emptor!"
withProcessContext menv $ upgradeCabal wc version
case mtools of
Just (Just (ToolGhcjs cv), _) ->
withProcessContext menv
$ ensureGhcjsBooted cv (soptsInstallIfMissing sopts) (soptsGHCJSBootOpts sopts)
_ -> return ()
when (soptsSanityCheck sopts) $ withProcessContext menv $ sanityCheck wc
return (mpaths, Just compilerBuild, needLocal)
-- | Determine which GHC builds to use depending on which shared libraries are available
-- on the system.
getGhcBuilds :: HasConfig env => RIO env [CompilerBuild]
getGhcBuilds = do
config <- view configL
case configGHCBuild config of
Just ghcBuild -> return [ghcBuild]
Nothing -> determineGhcBuild
where
determineGhcBuild = do
-- TODO: a more reliable, flexible, and data driven approach would be to actually download small
-- "test" executables (from setup-info) that link to the same gmp/tinfo versions
-- that GHC does (i.e. built in same environment as the GHC bindist). The algorithm would go
-- something like this:
--
-- check for previous 'uname -a'/`ldconfig -p` plus compiler version/variant in cache
-- if cached, then use that as suffix
-- otherwise:
-- download setup-info
-- go through all with right prefix for os/version/variant
-- first try "standard" (no extra suffix), then the rest
-- download "compatibility check" exe if not already downloaded
-- try running it
-- if successful, then choose that
-- cache compiler suffix with the uname -a and ldconfig -p output hash plus compiler version
--
-- Of course, could also try to make a static GHC bindist instead of all this rigamarole.
platform <- view platformL
case platform of
Platform _ Cabal.Linux -> do
-- Some systems don't have ldconfig in the PATH, so make sure to look in /sbin and /usr/sbin as well
let sbinEnv m = Map.insert
"PATH"
("/sbin:/usr/sbin" <> maybe "" (":" <>) (Map.lookup "PATH" m))
m
eldconfigOut
<- withModifyEnvVars sbinEnv
$ proc "ldconfig" ["-p"]
$ tryAny . fmap fst . readProcess_
let firstWords = case eldconfigOut of
Right ldconfigOut -> mapMaybe (listToMaybe . T.words) $
T.lines $ T.decodeUtf8With T.lenientDecode
$ LBS.toStrict ldconfigOut
Left _ -> []
checkLib lib
| libT `elem` firstWords = do
logDebug ("Found shared library " <> libD <> " in 'ldconfig -p' output")
return True
| osIsWindows =
-- Cannot parse /usr/lib on Windows
return False
| otherwise = do
-- This is a workaround for the fact that libtinfo.so.x doesn't appear in
-- the 'ldconfig -p' output on Arch or Slackware even when it exists.
-- There doesn't seem to be an easy way to get the true list of directories
-- to scan for shared libs, but this works for our particular cases.
let extraPaths = []
#if !WINDOWS
++ [$(mkAbsDir "/usr/lib"),$(mkAbsDir "/usr/lib64")]
#endif
matches <- filterM (doesFileExist .(</> lib)) extraPaths
case matches of
[] -> logDebug ("Did not find shared library " <> libD)
>> return False
(path:_) -> logDebug ("Found shared library " <> libD
<> " in " <> fromString (Path.toFilePath path))
>> return True
where
libT = T.pack (toFilePath lib)
libD = fromString (toFilePath lib)
hastinfo5 <- checkLib relFileLibtinfoSo5
hastinfo6 <- checkLib relFileLibtinfoSo6
hasncurses6 <- checkLib relFileLibncurseswSo6
hasgmp5 <- checkLib relFileLibgmpSo10
hasgmp4 <- checkLib relFileLibgmpSo3
let libComponents = concat
[ [["tinfo6"] | hastinfo6 && hasgmp5]
, [[] | hastinfo5 && hasgmp5]
, [["ncurses6"] | hasncurses6 && hasgmp5 ]
, [["gmp4"] | hasgmp4 ]
]
useBuilds $ map
(\c -> case c of
[] -> CompilerBuildStandard
_ -> CompilerBuildSpecialized (intercalate "-" c))
libComponents
#if !WINDOWS
Platform _ Cabal.FreeBSD -> do
let getMajorVer = readMaybe <=< headMaybe . (splitOn ".")
majorVer <- getMajorVer <$> sysRelease
if majorVer >= Just (12 :: Int) then
useBuilds [CompilerBuildSpecialized "ino64"]
else
useBuilds [CompilerBuildStandard]
Platform _ Cabal.OpenBSD -> do
releaseStr <- mungeRelease <$> sysRelease
useBuilds [CompilerBuildSpecialized releaseStr]
#endif
_ -> useBuilds [CompilerBuildStandard]
useBuilds builds = do
logDebug $
"Potential GHC builds: " <>
mconcat (intersperse ", " (map (fromString . compilerBuildName) builds))
return builds
#if !WINDOWS
-- | Encode an OpenBSD version (like "6.1") into a valid argument for
-- CompilerBuildSpecialized, so "maj6-min1". Later version numbers are prefixed
-- with "r".
-- The result r must be such that "ghc-" ++ r is a valid package name,
-- as recognized by parsePackageNameFromString.
mungeRelease :: String -> String
mungeRelease = intercalate "-" . prefixMaj . splitOn "."
where
prefixFst pfx k (rev : revs) = (pfx ++ rev) : k revs
prefixFst _ _ [] = []
prefixMaj = prefixFst "maj" prefixMin
prefixMin = prefixFst "min" (map ('r':))
sysRelease :: HasLogFunc env => RIO env String
sysRelease =
handleIO (\e -> do
logWarn $ "Could not query OS version" <> displayShow e
return "") .
liftIO .
alloca $ \ ptr ->
do throwErrnoIfMinus1_ "uname" $ uname ptr
peekCString $ release ptr
#endif
-- | Ensure Docker container-compatible 'stack' executable is downloaded
ensureDockerStackExe :: HasConfig env => Platform -> RIO env (Path Abs File)
ensureDockerStackExe containerPlatform = do
config <- view configL
containerPlatformDir <- runReaderT platformOnlyRelDir (containerPlatform,PlatformVariantNone)
let programsPath = configLocalProgramsBase config </> containerPlatformDir
tool = Tool (PackageIdentifier (mkPackageName "stack") stackVersion)
stackExeDir <- installDir programsPath tool
let stackExePath = stackExeDir </> relFileStack
stackExeExists <- doesFileExist stackExePath
unless stackExeExists $ do
logInfo $
"Downloading Docker-compatible " <>
fromString stackProgName <>
" executable"
sri <- downloadStackReleaseInfo Nothing Nothing (Just (versionString stackMinorVersion))
platforms <- runReaderT preferredPlatforms (containerPlatform, PlatformVariantNone)
downloadStackExe platforms sri stackExeDir False (const $ return ())
return stackExePath
-- | Install the newest version or a specific version of Cabal globally
upgradeCabal :: (HasConfig env, HasGHCVariant env)
=> WhichCompiler
-> UpgradeTo
-> RIO env ()
upgradeCabal wc upgradeTo = do
logWarn "Using deprecated --upgrade-cabal feature, this is not recommended"
logWarn "Manipulating the global Cabal is only for debugging purposes"
let name = mkPackageName "Cabal"
installed <- getCabalPkgVer wc
case upgradeTo of
Specific wantedVersion -> do
if installed /= wantedVersion then
doCabalInstall wc installed wantedVersion
else
logInfo $
"No install necessary. Cabal " <>
fromString (versionString installed) <>
" is already installed"
Latest -> do
mversion <- getLatestHackageVersion name UsePreferredVersions
case mversion of
Nothing -> throwString "No Cabal library found in index, cannot upgrade"
Just (PackageIdentifierRevision _name latestVersion _cabalHash) -> do
if installed < latestVersion then
doCabalInstall wc installed latestVersion
else
logInfo $
"No upgrade necessary: Cabal-" <>
fromString (versionString latestVersion) <>
" is the same or newer than latest hackage version " <>
fromString (versionString installed)
-- Configure and run the necessary commands for a cabal install
doCabalInstall :: (HasConfig env, HasGHCVariant env)
=> WhichCompiler
-> Version
-> Version
-> RIO env ()
doCabalInstall wc installed wantedVersion = do
when (wantedVersion >= mkVersion [2, 2]) $ do
logWarn "--upgrade-cabal will almost certainly fail for Cabal 2.2 or later"
logWarn "See: https://github.com/commercialhaskell/stack/issues/4070"
logWarn "Valiantly attempting to build it anyway, but I know this is doomed"
withSystemTempDir "stack-cabal-upgrade" $ \tmpdir -> do
logInfo $
"Installing Cabal-" <>
fromString (versionString wantedVersion) <>
" to replace " <>
fromString (versionString installed)
let name = mkPackageName "Cabal"
suffix <- parseRelDir $ "Cabal-" ++ versionString wantedVersion
let dir = tmpdir </> suffix
unpackPackageLocationRaw dir $ RPLIHackage
(PackageIdentifierRevision name wantedVersion CFILatest)
Nothing
compilerPath <- findExecutable (compilerExeName wc)
>>= either throwM parseAbsFile
versionDir <- parseRelDir $ versionString wantedVersion
let installRoot = toFilePath $ parent (parent compilerPath)
</> relDirNewCabal
</> versionDir
withWorkingDir (toFilePath dir) $ proc (compilerExeName wc) ["Setup.hs"] runProcess_
platform <- view platformL
let setupExe = dir </> case platform of
Platform _ Cabal.Windows -> relFileSetupExe
_ -> relFileSetupUpper
dirArgument name' = concat [ "--"
, name'
, "dir="
, installRoot FP.</> name'
]
args = "configure" : map dirArgument (words "lib bin data doc")
withWorkingDir (toFilePath dir) $ mapM_ (\args' -> proc (toFilePath setupExe) args' runProcess_)
[ args
, ["build"]
, ["install"]
]
logInfo "New Cabal library installed"
-- | Get the version of the system compiler, if available
getSystemCompiler
:: (HasProcessContext env, HasLogFunc env)
=> WhichCompiler
-> RIO env (Maybe (ActualCompiler, Arch))
getSystemCompiler wc = do
let exeName = case wc of
Ghc -> "ghc"
Ghcjs -> "ghcjs"
exists <- doesExecutableExist exeName
if exists
then do
eres <- proc exeName ["--info"] $ tryAny . fmap fst . readProcess_
let minfo = do
Right lbs <- Just eres
pairs_ <- readMaybe $ BL8.unpack lbs :: Maybe [(String, String)]
version <- lookup "Project version" pairs_ >>= parseVersionThrowing
arch <- lookup "Target platform" pairs_ >>= simpleParse . takeWhile (/= '-')
return (version, arch)
case (wc, minfo) of
(Ghc, Just (version, arch)) -> return (Just (ACGhc version, arch))
(Ghcjs, Just (_, arch)) -> do
eversion <- tryAny $ getCompilerVersion Ghcjs
case eversion of
Left _ -> return Nothing
Right version -> return (Just (version, arch))
(_, Nothing) -> return Nothing
else return Nothing
-- | Download the most recent SetupInfo
getSetupInfo :: HasConfig env => String -> RIO env SetupInfo
getSetupInfo stackSetupYaml = do
config <- view configL
setupInfos <-
mapM
loadSetupInfo
(SetupInfoFileOrURL stackSetupYaml :
configSetupInfoLocations config)
return (mconcat setupInfos)
where
loadSetupInfo (SetupInfoInline si) = return si
loadSetupInfo (SetupInfoFileOrURL urlOrFile) = do
bs <-
case parseUrlThrow urlOrFile of
Just req -> liftM (LBS.toStrict . getResponseBody) $ httpLbs req
Nothing -> liftIO $ S.readFile urlOrFile
WithJSONWarnings si warnings <- either throwM return (Yaml.decodeEither' bs)
when (urlOrFile /= defaultSetupInfoYaml) $
logJSONWarnings urlOrFile warnings
return si
getInstalledTool :: [Tool] -- ^ already installed
-> PackageName -- ^ package to find
-> (Version -> Bool) -- ^ which versions are acceptable
-> Maybe Tool
getInstalledTool installed name goodVersion =
if null available
then Nothing
else Just $ Tool $ maximumBy (comparing pkgVersion) available
where
available = mapMaybe goodPackage installed
goodPackage (Tool pi') =
if pkgName pi' == name &&
goodVersion (pkgVersion pi')
then Just pi'
else Nothing
goodPackage _ = Nothing
getInstalledGhcjs :: [Tool]
-> (ActualCompiler -> Bool)
-> Maybe Tool
getInstalledGhcjs installed goodVersion =
if null available
then Nothing
else Just $ ToolGhcjs $ maximum available
where
available = mapMaybe goodPackage installed
goodPackage (ToolGhcjs cv) = if goodVersion cv then Just cv else Nothing
goodPackage _ = Nothing
downloadAndInstallTool :: HasTerm env
=> Path Abs Dir
-> SetupInfo
-> DownloadInfo
-> Tool
-> (SetupInfo -> Path Abs File -> ArchiveType -> Path Abs Dir -> Path Abs Dir -> RIO env ())
-> RIO env Tool
downloadAndInstallTool programsDir si downloadInfo tool installer = do
ensureDir programsDir
(file, at) <- downloadFromInfo programsDir downloadInfo tool
dir <- installDir programsDir tool
tempDir <- tempInstallDir programsDir tool
liftIO $ ignoringAbsence (removeDirRecur tempDir)
ensureDir tempDir
unmarkInstalled programsDir tool
installer si file at tempDir dir
markInstalled programsDir tool
liftIO $ ignoringAbsence (removeDirRecur tempDir)
return tool
downloadAndInstallCompiler :: (HasConfig env, HasGHCVariant env)
=> CompilerBuild
-> SetupInfo
-> WantedCompiler
-> VersionCheck
-> Maybe String
-> RIO env Tool
downloadAndInstallCompiler ghcBuild si wanted@WCGhc{} versionCheck mbindistURL = do
ghcVariant <- view ghcVariantL
(selectedVersion, downloadInfo) <- case mbindistURL of
Just bindistURL -> do
case ghcVariant of
GHCCustom _ -> return ()
_ -> throwM RequireCustomGHCVariant
case wanted of
WCGhc version ->
return (version, GHCDownloadInfo mempty mempty DownloadInfo
{ downloadInfoUrl = T.pack bindistURL
, downloadInfoContentLength = Nothing
, downloadInfoSha1 = Nothing
, downloadInfoSha256 = Nothing
})
_ ->
throwM WantedMustBeGHC
_ -> do
ghcKey <- getGhcKey ghcBuild
case Map.lookup ghcKey $ siGHCs si of
Nothing -> throwM $ UnknownOSKey ghcKey
Just pairs_ -> getWantedCompilerInfo ghcKey versionCheck wanted ACGhc pairs_
config <- view configL
let installer =
case configPlatform config of
Platform _ Cabal.Windows -> installGHCWindows selectedVersion
_ -> installGHCPosix selectedVersion downloadInfo
logInfo $
"Preparing to install GHC" <>
(case ghcVariant of
GHCStandard -> ""
v -> " (" <> fromString (ghcVariantName v) <> ")") <>
(case ghcBuild of
CompilerBuildStandard -> ""
b -> " (" <> fromString (compilerBuildName b) <> ")") <>
" to an isolated location."