-
Notifications
You must be signed in to change notification settings - Fork 841
/
Setup.hs
1983 lines (1856 loc) · 87.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 TemplateHaskell #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE CPP #-}
module Stack.Setup
( setupEnv
, ensureCompiler
, ensureDockerStackExe
, getSystemCompiler
, getCabalInstallVersion
, SetupOpts (..)
, defaultSetupInfoYaml
, removeHaskellEnvVars
-- * 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.Char8 as S8
import qualified Data.ByteString.Lazy as LBS
import Data.Char (isSpace)
import Data.Conduit (Conduit, (=$), await, yield, awaitForever)
import Data.Conduit.Lazy (lazyConsume)
import Data.Conduit.Lift (evalStateC)
import qualified Data.Conduit.List as CL
import Data.Conduit.Zlib (ungzip)
import Data.Foldable (maximumBy)
import qualified Data.HashMap.Strict as HashMap
import Data.IORef.RunOnce (runOnce)
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 Lens.Micro (set)
import Network.HTTP.Simple (getResponseBody, httpLBS, withResponse, getResponseStatusCode)
import Network.HTTP.Download
import Path
import Path.CheckInstall (warnInstallSearchPathIssues)
import Path.Extra (toFilePathNoTrailingSep)
import Path.IO hiding (findExecutable, withSystemTempDir)
import Prelude (getLine, putStr, putStrLn, until)
import Stack.Build (build)
import Stack.Config (loadConfig)
import Stack.Constants (stackProgName)
import Stack.Constants.Config (distRelativeDir)
import Stack.Exec (defaultEnvSettings)
import Stack.Fetch
import Stack.GhcPkg (createDatabase, getCabalPkgVer, getGlobalDB, mkGhcPackagePath, ghcPkgPathEnvVar)
import Stack.Prelude
import Stack.PrettyPrint
import Stack.Setup.Installed
import Stack.Snapshot (loadSnapshot)
import Stack.Types.Build
import Stack.Types.Compiler
import Stack.Types.CompilerBuild
import Stack.Types.Config
import Stack.Types.Docker
import Stack.Types.PackageIdentifier
import Stack.Types.PackageName
import Stack.Types.Runner
import Stack.Types.Version
import qualified System.Directory as D
import System.Environment (getExecutablePath, lookupEnv)
import System.Exit (ExitCode (..), exitFailure)
import System.IO (stdout)
import System.IO.Error (isPermissionError)
import System.FilePath (searchPathSeparator)
import qualified System.FilePath as FP
import System.Process (rawSystem)
import System.Process.Log (withProcessTimeLog)
import System.Process.Read
import System.Process.Run (runCmd, Cmd(..))
import Text.Printf (printf)
#if !WINDOWS
import Bindings.Uname (uname, release)
import Data.List.Split (splitOn)
import Foreign.C (throwErrnoIfMinus1_, peekCString)
import Foreign.Marshal (alloca)
import System.Posix.Files (setFileMode)
#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 :: !(CompilerVersion 'CVWanted)
, 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 Text (CompilerVersion 'CVWanted) [CompilerVersion 'CVActual]
| UnknownOSKey Text
| GHCSanityCheckCompileFailed ReadProcessException (Path Abs File)
| WantedMustBeGHC
| RequireCustomGHCVariant
| ProblemWhileDecompressing (Path Abs File)
| SetupInfoMissingSevenz
| GHCJSRequiresStandardVariant
| GHCJSNotBooted
| DockerStackExeNotFound Version Text
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 oskey wanted known) = concat
[ "No information found for "
, compilerVersionString wanted
, ".\nSupported versions for OS key '" ++ T.unpack oskey ++ "': "
, intercalate ", " (map show 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"]
-- | Modify the environment variables (like PATH) appropriately, possibly doing installation too
setupEnv :: (HasBuildConfig env, HasGHCVariant env)
=> Maybe Text -- ^ Message to give user when necessary GHC is not available
-> RIO env EnvConfig
setupEnv mResolveMissingGHC = do
config <- view configL
bconfig <- view buildConfigL
let stackYaml = bcStackYaml bconfig
platform <- view platformL
wcVersion <- view wantedCompilerVersionL
wc <- view $ wantedCompilerVersionL.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, compilerBuild, _) <- ensureCompiler sopts
-- Modify the initial environment to include the GHC path, if a local GHC
-- is being used
menv0 <- getMinimalEnvOverride
env <- removeHaskellEnvVars
<$> augmentPathMap (maybe [] edBins mghcBin) (unEnvOverride menv0)
menv <- mkEnvOverride platform env
(compilerVer, cabalVer, globaldb) <- runConcurrently $ (,,)
<$> Concurrently (getCompilerVersion menv wc)
<*> Concurrently (getCabalPkgVer menv wc)
<*> Concurrently (getGlobalDB menv wc)
logDebug "Resolving package entries"
packagesRef <- liftIO $ newIORef Nothing
bc <- view buildConfigL
-- 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 in loadSnapshot.
let bcPath :: BuildConfig
bcPath = set envOverrideL (const (return menv)) bc
ls <- runRIO bcPath $ loadSnapshot
(Just compilerVer)
(view projectRootL bc)
(bcSnapshotDef bc)
let envConfig0 = EnvConfig
{ envConfigBuildConfig = bc
, envConfigCabalVersion = cabalVer
, envConfigCompilerVersion = compilerVer
, envConfigCompilerBuild = compilerBuild
, envConfigPackagesRef = packagesRef
, envConfigLoadedSnapshot = ls
}
-- extra installation bin directories
mkDirs <- runReaderT extraBinDirs envConfig0
let mpath = Map.lookup "PATH" env
depsPath <- augmentPath (mkDirs False) mpath
localsPath <- augmentPath (mkDirs True) mpath
deps <- runReaderT packageDatabaseDeps envConfig0
createDatabase menv wc deps
localdb <- runReaderT packageDatabaseLocal envConfig0
createDatabase menv wc localdb
extras <- runReaderT packageDatabaseExtra envConfig0
let mkGPP locals = mkGhcPackagePath locals localdb deps extras globaldb
distDir <- runReaderT distRelativeDir envConfig0
executablePath <- liftIO getExecutablePath
utf8EnvVars <- getUtf8EnvVars menv compilerVer
mGhcRtsEnvVar <- liftIO $ lookupEnv "GHCRTS"
envRef <- liftIO $ newIORef Map.empty
let getEnvOverride' es = do
m <- readIORef envRef
case Map.lookup es m of
Just eo -> return eo
Nothing -> do
eo <- mkEnvOverride platform
$ 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
return EnvConfig
{ envConfigBuildConfig = bconfig
{ bcConfig = maybe id addIncludeLib mghcBin
(view configL bconfig)
{ configEnvOverride = getEnvOverride' }
}
, envConfigCabalVersion = cabalVer
, envConfigCompilerVersion = compilerVer
, envConfigCompilerBuild = compilerBuild
, envConfigPackagesRef = envConfigPackagesRef envConfig0
, envConfigLoadedSnapshot = ls
}
-- | 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, CompilerBuild, Bool)
ensureCompiler sopts = do
let wc = whichCompiler (soptsWantedCompiler sopts)
when (getGhcVersion (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 ""
-- Check the available GHCs
menv0 <- getMinimalEnvOverride
msystem <-
if soptsUseSystem sopts
then do
logDebug "Getting system compiler version"
getSystemCompiler menv0 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' <- runOnce (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 <- 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
(installedCompiler, compilerBuild) <-
case wc of
Ghc -> do
ghcBuild <- getGhcBuild menv0
ghcPkgName <- parsePackageNameFromString ("ghc" ++ ghcVariantSuffix ghcVariant ++ compilerBuildSuffix ghcBuild)
return (getInstalledTool installed ghcPkgName (isWanted . GhcVersion), ghcBuild)
Ghcjs -> return (getInstalledGhcjs installed isWanted, CompilerBuildStandard)
compilerTool <- case (installedCompiler, soptsForceReinstall sopts) of
(Just tool, False) -> return tool
_
| soptsInstallIfMissing sopts -> do
si <- getSetupInfo'
downloadAndInstallCompiler
compilerBuild
si
(soptsWantedCompiler sopts)
(soptsCompilerCheck sopts)
(soptsGHCBindistURL sopts)
| otherwise -> do
recommendSystemGhc <-
if soptsUseSystem sopts
then return False
else do
msystemGhc <- getSystemCompiler menv0 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
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 -> return menv0
Just ed -> do
config <- view configL
m <- augmentPathMap (edBins ed) (unEnvOverride menv0)
mkEnvOverride (configPlatform config) (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!"
upgradeCabal menv wc version
case mtools of
Just (Just (ToolGhcjs cv), _) -> ensureGhcjsBooted menv cv (soptsInstallIfMissing sopts) (soptsGHCJSBootOpts sopts)
_ -> return ()
when (soptsSanityCheck sopts) $ sanityCheck menv wc
return (mpaths, compilerBuild, needLocal)
-- | Determine which GHC build to use depending on which shared libraries are available
-- on the system.
getGhcBuild :: HasConfig env => EnvOverride -> RIO env CompilerBuild
getGhcBuild menv = 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
sbinEnv <- modifyEnvOverride menv $
Map.insert "PATH" $
"/sbin:/usr/sbin" <>
maybe "" (":" <>) (Map.lookup "PATH" (eoTextMap menv))
eldconfigOut <- tryProcessStdout Nothing sbinEnv "ldconfig" ["-p"]
egccErrOut <- tryProcessStderrStdout Nothing menv "gcc" ["-v"]
let firstWords = case eldconfigOut of
Right ldconfigOut -> mapMaybe (listToMaybe . T.words) $
T.lines $ T.decodeUtf8With T.lenientDecode ldconfigOut
Left _ -> []
checkLib lib
| libT `elem` firstWords = do
logDebug ("Found shared library " <> libT <> " in 'ldconfig -p' output")
return True
| otherwise = do
#ifdef WINDOWS
-- (mkAbsDir "/usr/lib") fails to compile on Windows, thus the CPP
return False
#else
-- This is a workaround for the fact that libtinfo.so.6 doesn't appear in
-- the 'ldconfig -p' output on Arch 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 case.
e <- doesFileExist ($(mkAbsDir "/usr/lib") </> lib)
if e
then logDebug ("Found shared library " <> libT <> " in /usr/lib")
else logDebug ("Did not find shared library " <> libT)
return e
#endif
where
libT = T.pack (toFilePath lib)
noPie = case egccErrOut of
Right (gccErr,gccOut) ->
"--enable-default-pie" `elem` S8.words gccOutput || "Gentoo Hardened" `S8.isInfixOf` gccOutput
where gccOutput = gccOut <> gccErr
Left _ -> False
logDebug $ if noPie
then "PIE disabled"
else "PIE enabled"
hastinfo5 <- checkLib $(mkRelFile "libtinfo.so.5")
hastinfo6 <- checkLib $(mkRelFile "libtinfo.so.6")
hasncurses6 <- checkLib $(mkRelFile "libncursesw.so.6")
hasgmp5 <- checkLib $(mkRelFile "libgmp.so.10")
hasgmp4 <- checkLib $(mkRelFile "libgmp.so.3")
let libComponents =
if | hastinfo6 && hasgmp5 -> ["tinfo6"]
| hastinfo5 && hasgmp5 -> []
| hasncurses6 && hasgmp5 -> ["ncurses6"]
| hasgmp4 && hastinfo5 -> ["gmp4"]
| otherwise -> []
pieComponents =
if noPie
then ["nopie"]
else []
case libComponents ++ pieComponents of
[] -> useBuild CompilerBuildStandard
components -> useBuild (CompilerBuildSpecialized (intercalate "-" components))
#if !WINDOWS
Platform _ Cabal.OpenBSD -> do
releaseStr <- mungeRelease <$> sysRelease
useBuild (CompilerBuildSpecialized releaseStr)
#endif
_ -> useBuild CompilerBuildStandard
useBuild CompilerBuildStandard = do
logDebug "Using standard GHC build"
return CompilerBuildStandard
useBuild (CompilerBuildSpecialized s) = do
logDebug ("Using " <> T.pack s <> " GHC build")
return (CompilerBuildSpecialized s)
#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 :: (MonadUnliftIO m, MonadLogger m) => m String
sysRelease =
handleIO (\e -> do
logWarn $ T.concat [ T.pack "Could not query OS version"
, T.pack $ show 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 </> $(mkRelFile "stack")
stackExeExists <- doesFileExist stackExePath
unless stackExeExists $ do
logInfo $ mconcat ["Downloading Docker-compatible ", T.pack 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)
=> EnvOverride
-> WhichCompiler
-> UpgradeTo
-> RIO env ()
upgradeCabal menv wc upgradeTo = do
logInfo "Manipulating the global Cabal is only for debugging purposes"
let name = $(mkPackageName "Cabal")
rmap <- resolvePackages Nothing mempty (Set.singleton name)
installed <- getCabalPkgVer menv wc
case upgradeTo of
Specific wantedVersion -> do
if installed /= wantedVersion then
doCabalInstall menv wc installed wantedVersion
else
logInfo $ T.concat ["No install necessary. Cabal "
, T.pack $ versionString installed
, " is already installed"]
Latest -> case map rpIdent rmap of
[] -> throwString "No Cabal library found in index, cannot upgrade"
[PackageIdentifier name' latestVersion] | name == name' -> do
if installed < latestVersion then
doCabalInstall menv wc installed latestVersion
else
logInfo $ T.concat
[ "No upgrade necessary: Cabal-"
, T.pack $ versionString latestVersion
, " is the same or newer than latest hackage version "
, T.pack $ versionString installed
]
x -> error $ "Unexpected results for resolvePackages: " ++ show x
-- Configure and run the necessary commands for a cabal install
doCabalInstall :: (HasConfig env, HasGHCVariant env)
=> EnvOverride
-> WhichCompiler
-> Version
-> Version
-> RIO env ()
doCabalInstall menv wc installed wantedVersion = do
withSystemTempDir "stack-cabal-upgrade" $ \tmpdir -> do
logInfo $ T.concat
[ "Installing Cabal-"
, T.pack $ versionString wantedVersion
, " to replace "
, T.pack $ versionString installed
]
let name = $(mkPackageName "Cabal")
ident = PackageIdentifier name wantedVersion
m <- unpackPackageIdents tmpdir Nothing [PackageIdentifierRevision ident CFILatest]
compilerPath <- join $ findExecutable menv (compilerExeName wc)
versionDir <- parseRelDir $ versionString wantedVersion
let installRoot = toFilePath $ parent (parent compilerPath)
</> $(mkRelDir "new-cabal")
</> versionDir
dir <- case Map.lookup ident m of
Nothing -> error "upgradeCabal: Invariant violated, dir missing"
Just dir -> return dir
runCmd (Cmd (Just dir) (compilerExeName wc) menv ["Setup.hs"]) Nothing
platform <- view platformL
let setupExe = toFilePath $ dir </> case platform of
Platform _ Cabal.Windows -> $(mkRelFile "Setup.exe")
_ -> $(mkRelFile "Setup")
dirArgument name' = concat [ "--"
, name'
, "dir="
, installRoot FP.</> name'
]
args = "configure" : map dirArgument (words "lib bin data doc")
runCmd (Cmd (Just dir) setupExe menv args) Nothing
runCmd (Cmd (Just dir) setupExe menv ["build"]) Nothing
runCmd (Cmd (Just dir) setupExe menv ["install"]) Nothing
logInfo "New Cabal library installed"
-- | Get the version of the system compiler, if available
getSystemCompiler
:: HasLogFunc env
=> EnvOverride
-> WhichCompiler
-> RIO env (Maybe (CompilerVersion 'CVActual, Arch))
getSystemCompiler menv wc = do
let exeName = case wc of
Ghc -> "ghc"
Ghcjs -> "ghcjs"
exists <- doesExecutableExist menv exeName
if exists
then do
eres <- tryProcessStdout Nothing menv exeName ["--info"]
let minfo = do
Right bs <- Just eres
pairs_ <- readMaybe $ S8.unpack bs :: Maybe [(String, String)]
version <- lookup "Project version" pairs_ >>= parseVersionFromString
arch <- lookup "Target platform" pairs_ >>= simpleParse . takeWhile (/= '-')
return (version, arch)
case (wc, minfo) of
(Ghc, Just (version, arch)) -> return (Just (GhcVersion version, arch))
(Ghcjs, Just (_, arch)) -> do
eversion <- tryAny $ getCompilerVersion menv 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 packageIdentifierVersion) available
where
available = mapMaybe goodPackage installed
goodPackage (Tool pi') =
if packageIdentifierName pi' == name &&
goodVersion (packageIdentifierVersion pi')
then Just pi'
else Nothing
goodPackage _ = Nothing
getInstalledGhcjs :: [Tool]
-> (CompilerVersion 'CVActual -> 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 :: HasRunner 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
-> CompilerVersion 'CVWanted
-> VersionCheck
-> Maybe String
-> RIO env Tool
downloadAndInstallCompiler ghcBuild si wanted@GhcVersion{} versionCheck mbindistURL = do
ghcVariant <- view ghcVariantL
(selectedVersion, downloadInfo) <- case mbindistURL of
Just bindistURL -> do
case ghcVariant of
GHCCustom _ -> return ()
_ -> throwM RequireCustomGHCVariant
case wanted of
GhcVersion 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 GhcVersion 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 -> " (" <> T.pack (ghcVariantName v) <> ")") <>
(case ghcBuild of
CompilerBuildStandard -> ""
b -> " (" <> T.pack (compilerBuildName b) <> ")") <>
" to an isolated location."
logInfo "This will not interfere with any system-level installation."
ghcPkgName <- parsePackageNameFromString ("ghc" ++ ghcVariantSuffix ghcVariant ++ compilerBuildSuffix ghcBuild)
let tool = Tool $ PackageIdentifier ghcPkgName selectedVersion
downloadAndInstallTool (configLocalPrograms config) si (gdiDownloadInfo downloadInfo) tool installer
downloadAndInstallCompiler compilerBuild si wanted versionCheck _mbindistUrl = do
config <- view configL
ghcVariant <- view ghcVariantL
case (ghcVariant, compilerBuild) of
(GHCStandard, CompilerBuildStandard) -> return ()
_ -> throwM GHCJSRequiresStandardVariant
(selectedVersion, downloadInfo) <- case Map.lookup "source" $ siGHCJSs si of
Nothing -> throwM $ UnknownOSKey "source"
Just pairs_ -> getWantedCompilerInfo "source" versionCheck wanted id pairs_
logInfo "Preparing to install GHCJS to an isolated location."
logInfo "This will not interfere with any system-level installation."
let tool = ToolGhcjs selectedVersion
downloadAndInstallTool (configLocalPrograms config) si downloadInfo tool installGHCJS
getWantedCompilerInfo :: (Ord k, MonadThrow m)
=> Text
-> VersionCheck
-> CompilerVersion 'CVWanted
-> (k -> CompilerVersion 'CVActual)
-> Map k a
-> m (k, a)
getWantedCompilerInfo key versionCheck wanted toCV pairs_ =
case mpair of
Just pair -> return pair
Nothing -> throwM $ UnknownCompilerVersion key wanted (map toCV (Map.keys pairs_))
where
mpair =
listToMaybe $
sortBy (flip (comparing fst)) $
filter (isWantedCompiler versionCheck wanted . toCV . fst) (Map.toList pairs_)
getGhcKey :: (MonadReader env m, HasPlatform env, HasGHCVariant env, MonadThrow m)
=> CompilerBuild -> m Text
getGhcKey ghcBuild = do
ghcVariant <- view ghcVariantL
platform <- view platformL
osKey <- getOSKey platform
return $ osKey <> T.pack (ghcVariantSuffix ghcVariant) <> T.pack (compilerBuildSuffix ghcBuild)
getOSKey :: (MonadThrow m)
=> Platform -> m Text
getOSKey platform =
case platform of
Platform I386 Cabal.Linux -> return "linux32"
Platform X86_64 Cabal.Linux -> return "linux64"
Platform I386 Cabal.OSX -> return "macosx"
Platform X86_64 Cabal.OSX -> return "macosx"
Platform I386 Cabal.FreeBSD -> return "freebsd32"
Platform X86_64 Cabal.FreeBSD -> return "freebsd64"
Platform I386 Cabal.OpenBSD -> return "openbsd32"
Platform X86_64 Cabal.OpenBSD -> return "openbsd64"
Platform I386 Cabal.Windows -> return "windows32"
Platform X86_64 Cabal.Windows -> return "windows64"
Platform Arm Cabal.Linux -> return "linux-armv7"
Platform arch os -> throwM $ UnsupportedSetupCombo os arch
downloadFromInfo
:: HasRunner env
=> Path Abs Dir -> DownloadInfo -> Tool -> RIO env (Path Abs File, ArchiveType)
downloadFromInfo programsDir downloadInfo tool = do
at <-
case extension of
".tar.xz" -> return TarXz
".tar.bz2" -> return TarBz2
".tar.gz" -> return TarGz
".7z.exe" -> return SevenZ
_ -> throwString $ "Error: Unknown extension for url: " ++ url
relativeFile <- parseRelFile $ toolString tool ++ extension
path <- case url of
(parseUrlThrow -> Just _) -> do
let path = programsDir </> relativeFile
ensureDir programsDir
chattyDownload (T.pack (toolString tool)) downloadInfo path
return path
(parseAbsFile -> Just path) -> do
let DownloadInfo{downloadInfoContentLength=contentLength, downloadInfoSha1=sha1,
downloadInfoSha256=sha256} =
downloadInfo
when (isJust contentLength) $
logWarn ("`content-length` in not checked \n" <>
"and should not be specified when `url` is a file path")
when (isJust sha1) $
logWarn ("`sha1` is not checked and \n" <>
"should not be specified when `url` is a file path")
when (isJust sha256) $
logWarn ("`sha256` is not checked and \n" <>
"should not be specified when `url` is a file path")
return path
_ ->
throwString $ "Error: `url` must be either an HTTP URL or absolute file path: " ++ url
return (path, at)
where
url = T.unpack $ downloadInfoUrl downloadInfo
extension = loop url
where
loop fp
| ext `elem` [".tar", ".bz2", ".xz", ".exe", ".7z", ".gz"] = loop fp' ++ ext
| otherwise = ""
where
(fp', ext) = FP.splitExtension fp
data ArchiveType
= TarBz2
| TarXz
| TarGz
| SevenZ
installGHCPosix :: HasConfig env
=> Version
-> GHCDownloadInfo
-> SetupInfo