hie-bios 0.21.0 → 0.22.0
raw patch · 21 files changed
+597/−336 lines, 21 filesdep +unixdep ~aesonPVP ok
version bump matches the API change (PVP)
Dependencies added: unix
Dependency ranges changed: aeson
API changes (from Hackage documentation)
- HIE.Bios: [cradleCacheDir] :: CradleRunConfig -> Maybe CacheDir
- HIE.Bios.Cradle: [cradleCacheDir] :: CradleRunConfig -> Maybe CacheDir
- HIE.Bios.Cradle.Resolved: [cradleCacheDirResolved] :: ResolvedCradles a -> CacheDir
- HIE.Bios.Environment: getCacheDir :: FilePath -> IO CacheDir
- HIE.Bios.Environment: resolveCacheDir :: FilePath -> Maybe CacheDir -> IO CacheDir
- HIE.Bios.Process: cacheFile :: FilePath -> String -> (FilePath -> IO ()) -> IO FilePath
- HIE.Bios.Types: [cradleCacheDir] :: CradleRunConfig -> Maybe CacheDir
+ HIE.Bios: [cradleCacheRootDir] :: CradleRunConfig -> Maybe CacheRootDir
+ HIE.Bios.Config: UnknownKeys :: JSONPath -> [Key] -> [Key] -> ConfigWarning
+ HIE.Bios.Config: [knownKeys] :: ConfigWarning -> [Key]
+ HIE.Bios.Config: [unknownKeysIn] :: ConfigWarning -> JSONPath
+ HIE.Bios.Config: [unknownKeys] :: ConfigWarning -> [Key]
+ HIE.Bios.Config: data ConfigWarning
+ HIE.Bios.Config: readConfigWithWarnings :: FromJSON a => FilePath -> IO ([ConfigWarning], Config a)
+ HIE.Bios.Config.YAML: UnknownKeys :: JSONPath -> [Key] -> [Key] -> ConfigWarning
+ HIE.Bios.Config.YAML: [knownKeys] :: ConfigWarning -> [Key]
+ HIE.Bios.Config.YAML: [unknownKeysIn] :: ConfigWarning -> JSONPath
+ HIE.Bios.Config.YAML: [unknownKeys] :: ConfigWarning -> [Key]
+ HIE.Bios.Config.YAML: configWarnings :: Value -> [ConfigWarning]
+ HIE.Bios.Config.YAML: data ConfigWarning
+ HIE.Bios.Config.YAML: instance GHC.Classes.Eq HIE.Bios.Config.YAML.ConfigWarning
+ HIE.Bios.Config.YAML: instance GHC.Show.Show HIE.Bios.Config.YAML.ConfigWarning
+ HIE.Bios.Cradle: [cradleCacheRootDir] :: CradleRunConfig -> Maybe CacheRootDir
+ HIE.Bios.Cradle.Resolved: [cradleCacheRootDirResolved] :: ResolvedCradles a -> CacheRootDir
+ HIE.Bios.Environment: resolveCacheDirIn :: FilePath -> Maybe CacheRootDir -> IO CacheDir
+ HIE.Bios.Environment: resolveCacheRootDir :: Maybe CacheRootDir -> IO CacheRootDir
+ HIE.Bios.Process: writeFileNoInherit :: FilePath -> String -> IO ()
+ HIE.Bios.Types: CacheRootDir :: FilePath -> CacheRootDir
+ HIE.Bios.Types: LogConfigWarning :: FilePath -> ConfigWarning -> Log
+ HIE.Bios.Types: [cradleCacheRootDir] :: CradleRunConfig -> Maybe CacheRootDir
+ HIE.Bios.Types: [unCacheRootDir] :: CacheRootDir -> FilePath
+ HIE.Bios.Types: instance Data.String.IsString HIE.Bios.Types.CacheRootDir
+ HIE.Bios.Types: instance GHC.Classes.Eq HIE.Bios.Types.CacheRootDir
+ HIE.Bios.Types: instance GHC.Show.Show HIE.Bios.Types.CacheRootDir
+ HIE.Bios.Types: newtype CacheRootDir
- HIE.Bios: CradleError :: [FilePath] -> ExitCode -> [String] -> [FilePath] -> CradleError
+ HIE.Bios: CradleError :: [FilePath] -> Either IOError ExitCode -> [String] -> [FilePath] -> CradleError
- HIE.Bios: CradleRunConfig :: Maybe CacheDir -> CradleRunConfig
+ HIE.Bios: CradleRunConfig :: Maybe CacheRootDir -> CradleRunConfig
- HIE.Bios: [cradleErrorExitCode] :: CradleError -> ExitCode
+ HIE.Bios: [cradleErrorExitCode] :: CradleError -> Either IOError ExitCode
- HIE.Bios.Cradle: CradleRunConfig :: Maybe CacheDir -> CradleRunConfig
+ HIE.Bios.Cradle: CradleRunConfig :: Maybe CacheRootDir -> CradleRunConfig
- HIE.Bios.Cradle.Cabal: cabalBuildDir :: CacheDir -> FilePath -> IO FilePath
+ HIE.Bios.Cradle.Cabal: cabalBuildDir :: CacheRootDir -> FilePath -> IO CacheDir
- HIE.Bios.Cradle.Cabal: withGhcWrapperTool :: LogAction IO (WithSeverity Log) -> CacheDir -> GhcProc -> FilePath -> IO FilePath
+ HIE.Bios.Cradle.Cabal: withGhcWrapperTool :: LogAction IO (WithSeverity Log) -> CacheRootDir -> GhcProc -> FilePath -> IO FilePath
- HIE.Bios.Cradle.Resolved: ResolvedCradles :: FilePath -> [ResolvedCradle a] -> ProgramVersions -> CacheDir -> ResolvedCradles a
+ HIE.Bios.Cradle.Resolved: ResolvedCradles :: FilePath -> [ResolvedCradle a] -> ProgramVersions -> CacheRootDir -> ResolvedCradles a
- HIE.Bios.Environment: initSession' :: GhcMonad m => Maybe CacheDir -> ComponentOptions -> m [Target]
+ HIE.Bios.Environment: initSession' :: GhcMonad m => Maybe CacheRootDir -> ComponentOptions -> m [Target]
- HIE.Bios.Ghc.Api: initSessionWithMessage' :: GhcMonad m => Maybe CacheDir -> Maybe Messager -> ComponentOptions -> (m SuccessFlag, ComponentOptions)
+ HIE.Bios.Ghc.Api: initSessionWithMessage' :: GhcMonad m => Maybe CacheRootDir -> Maybe Messager -> ComponentOptions -> (m SuccessFlag, ComponentOptions)
- HIE.Bios.Types: CradleError :: [FilePath] -> ExitCode -> [String] -> [FilePath] -> CradleError
+ HIE.Bios.Types: CradleError :: [FilePath] -> Either IOError ExitCode -> [String] -> [FilePath] -> CradleError
- HIE.Bios.Types: CradleRunConfig :: Maybe CacheDir -> CradleRunConfig
+ HIE.Bios.Types: CradleRunConfig :: Maybe CacheRootDir -> CradleRunConfig
- HIE.Bios.Types: [cradleErrorExitCode] :: CradleError -> ExitCode
+ HIE.Bios.Types: [cradleErrorExitCode] :: CradleError -> Either IOError ExitCode
Files
- ChangeLog.md +8/−0
- hie-bios.cabal +20/−11
- src/HIE/Bios/Config.hs +15/−4
- src/HIE/Bios/Config/YAML.hs +85/−56
- src/HIE/Bios/Cradle.hs +18/−15
- src/HIE/Bios/Cradle/Cabal.hs +35/−33
- src/HIE/Bios/Cradle/Resolved.hs +1/−1
- src/HIE/Bios/Environment.hs +53/−50
- src/HIE/Bios/Flags.hs +2/−2
- src/HIE/Bios/Ghc/Api.hs +1/−1
- src/HIE/Bios/Ghc/Gap.hs +1/−1
- src/HIE/Bios/Ghc/Logger.hs +8/−1
- src/HIE/Bios/Process.hs +56/−27
- src/HIE/Bios/Types.hs +24/−4
- tests/BiosTests.hs +63/−73
- tests/ParserTests.hs +31/−21
- tests/Utils.hs +149/−29
- tests/configs/cabal-unknown-key.yaml +4/−0
- tests/configs/multi-unknown-keys.yaml +16/−0
- wrappers/cabal +4/−4
- wrappers/cabal-with-repl +3/−3
ChangeLog.md view
@@ -1,5 +1,13 @@ # ChangeLog hie-bios +## 2026-12-02 - 0.22.0++* Support projects that use UTF-8 encoding in the directory ([#531](https://github.com/haskell/hie-bios/pull/531))+ * Use posix shell for cabal wrapper scripts ([#533](https://github.com/haskell/hie-bios/pull/533))+* Warn about unknown keys in `hie.yaml` instead of failing ([#534](https://github.com/haskell/hie-bios/pull/534))+* Support GHC 9.14.2 ([#527](https://github.com/haskell/hie-bios/pull/527))+* Include process exception in cradle error output ([#530](https://github.com/haskell/hie-bios/pull/530))+ ## 2026-07-30 - 0.21.0 * Add a CI timeout on tests ([#521](https://github.com/haskell/hie-bios/pull/521)).
hie-bios.cabal view
@@ -1,6 +1,6 @@ cabal-version: 2.2 name: hie-bios-version: 0.21.0+version: 0.22.0 author: Matthew Pickering <matthewtpickering@gmail.com>, Hannes Siebenhandl <fendor.haskell@gmail.com> maintainer: Hannes Siebenhandl <fendor.haskell@gmail.com> license: BSD-3-Clause@@ -13,6 +13,7 @@ extra-doc-files: ChangeLog.md README.md+ extra-source-files: tests/configs/*.yaml tests/projects/cabal-with-custom-setup-old/a-with-custom/a-with-custom.cabal@@ -161,9 +162,18 @@ tested-with: ghc ==9.6.7 || ==9.8.4 || ==9.10.1 || ==9.12.2 || ==9.14.1 +common runopts+ ghc-options:+ -threaded+ -rtsopts++common compopts+ ghc-options:+ -Wall+ library+ import: compopts default-language: Haskell2010- ghc-options: -Wall hs-source-dirs: src exposed-modules: HIE.Bios@@ -191,7 +201,7 @@ other-modules: Paths_hie_bios autogen-modules: Paths_hie_bios build-depends:- aeson >=1.4.4 && <2.4,+ aeson >=2 && <2.4, base >=4.16 && <5, base16-bytestring >=0.1.1 && <1.1, bytestring >=0.10.8 && <0.13,@@ -218,12 +228,16 @@ unordered-containers >=0.2.9 && <0.3, yaml >=0.10.0 && <0.12, + if !os(windows)+ build-depends:+ unix >=2.8 && <2.9+ executable hie-bios+ import: compopts, runopts default-language: Haskell2010 main-is: Main.hs other-modules: Paths_hie_bios autogen-modules: Paths_hie_bios- ghc-options: -Wall hs-source-dirs: exe build-depends: base >=4.16 && <5,@@ -235,6 +249,7 @@ prettyprinter, test-suite parser-tests+ import: compopts, runopts type: exitcode-stdio-1.0 default-language: Haskell2010 build-depends:@@ -247,13 +262,10 @@ yaml, hs-source-dirs: tests/- ghc-options:- -threaded- -Wall- main-is: ParserTests.hs test-suite bios-tests+ import: compopts, runopts type: exitcode-stdio-1.0 default-language: Haskell2010 build-depends:@@ -277,9 +289,6 @@ hs-source-dirs: tests/ main-is: BiosTests.hs other-modules: Utils- ghc-options:- -threaded- -Wall -- There seems to be a race condition on windows if !os(windows)
src/HIE/Bios/Config.hs view
@@ -5,6 +5,8 @@ -- | Logic and datatypes for parsing @hie.yaml@ files. module HIE.Bios.Config( readConfig,+ readConfigWithWarnings,+ ConfigWarning(..), Config(..), CradleConfig(..), CabalType,@@ -28,7 +30,7 @@ import Data.Yaml import Data.Yaml.Internal (Warning(..)) -import HIE.Bios.Config.YAML (CradleConfigYAML)+import HIE.Bios.Config.YAML (CradleConfigYAML, ConfigWarning(..)) import qualified HIE.Bios.Config.YAML as YAML @@ -150,12 +152,21 @@ show (Multi a) = "Multi " ++ show a show (Other _ val) = "Other {originalYamlValue = " ++ show val ++ "}" +-- | Read a @hie.yaml@ file. Keys that hie-bios doesn't know about are+-- ignored; use 'readConfigWithWarnings' to find out about them. readConfig :: FromJSON a => FilePath -> IO (Config a)-readConfig fp = do+readConfig fp = snd <$> readConfigWithWarnings fp++-- | Like 'readConfig', but also returns warnings about the parts of the file+-- that were ignored, such as keys hie-bios doesn't know about.+readConfigWithWarnings :: FromJSON a => FilePath -> IO ([ConfigWarning], Config a)+readConfigWithWarnings fp = do result <- decodeFileWithWarnings fp- fmap fromYAMLConfig $ either throwIO failOnAnyDuplicate result+ value <- either throwIO failOnAnyDuplicate result+ config <- either (throwIO . AesonException) pure (parseEither parseJSON value)+ pure (YAML.configWarnings value, fromYAMLConfig config) where- failOnAnyDuplicate :: ([Warning], CradleConfigYAML a) -> IO (CradleConfigYAML a)+ failOnAnyDuplicate :: ([Warning], Value) -> IO Value failOnAnyDuplicate (warnings, config) = do _ <- case mapMaybe failOnDuplicate warnings of dups@(_:_) -> throwIO $ InvalidYaml $ Just $ YamlException
src/HIE/Bios/Config/YAML.hs view
@@ -2,7 +2,6 @@ {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE OverloadedStrings #-}-{-# LANGUAGE CPP #-} -- | Datatypes for parsing @hie.yaml@ files module HIE.Bios.Config.YAML@@ -19,48 +18,86 @@ , OtherConfig(..) , OneOrManyComponents(..) , Callable(..)+ , ConfigWarning(..)+ , configWarnings ) where import Control.Applicative ((<|>)) import Data.Aeson-#if MIN_VERSION_aeson(2,0,0)-import Data.Aeson.KeyMap (keys,lookup)-#else-import Data.HashMap.Strict (lookup)-import qualified Data.HashMap.Strict as Map-import qualified Data.Text as T-#endif-import Data.Aeson.Types (Parser, typeMismatch)+import Data.Aeson.KeyMap (keys, lookup)+import qualified Data.Aeson.KeyMap as KM+import Data.Aeson.Types (JSONPathElement (..), Parser, typeMismatch) import qualified Data.Char as C (toLower)+import qualified Data.Foldable as F import Data.List ((\\)) import GHC.Generics (Generic) import Prelude hiding (lookup) -#if !MIN_VERSION_aeson(2,0,0)--- | Backwards compatible type-def for Key--- This used to be just a Text, but since aeson >= 2--- this is an opaque datatype.-type Key = T.Text--- | Backwards compatible type-def for KeyMap--- This used to be just a HashMap, but since aeson >= 2--- this is an opaque datatype.-type KeyMap v = Map.HashMap T.Text v+-- | Something in a @hie.yaml@ file that hie-bios doesn't recognise. It is+-- ignored rather than rejected, so that a file written for a newer hie-bios+-- can still be used by an older one.+data ConfigWarning+ = UnknownKeys+ { unknownKeysIn :: JSONPath+ -- ^ Where the keys were found, e.g. @$.cradle.cabal@.+ , unknownKeys :: [Key]+ , knownKeys :: [Key]+ }+ deriving (Show, Eq) -keys :: KeyMap v -> [Key]-keys = Map.keys-#endif+-- The keys each part of the configuration accepts.+cabalConfigKeys, cabalComponentKeys, stackConfigKeys, stackComponentKeys, biosConfigKeys :: [Key]+cabalConfigKeys = ["cabalProject", "component", "components", "componentsToLoad"]+cabalComponentKeys = ["path", "component", "cabalProject"]+stackConfigKeys = ["component", "components", "stackYaml", "componentsToLoad"]+stackComponentKeys = ["path", "component", "stackYaml"]+biosConfigKeys = ["program", "shell", "dependency-program", "dependency-shell", "with-ghc"] -checkObjectKeys :: [Key] -> Object -> Parser ()-checkObjectKeys allowedKeys obj =- let extraKeys = keys obj \\ allowedKeys- in case extraKeys of- [] -> pure ()- _ -> fail $ mconcat [ "Unexpected keys "- , show extraKeys- , ", keys allowed: "- , show allowedKeys- ]+-- | Find the keys in the @cradle@ section of a @hie.yaml@ file, given as an+-- unparsed 'Value', that hie-bios doesn't know about.+configWarnings :: Value -> [ConfigWarning]+configWarnings = inConfig []+ where+ inConfig at (Object o) = maybe [] (inCradle (at ++ [Key "cradle"])) (lookup "cradle" o)+ inConfig _ _ = [] + inCradle at (Object o) = concat+ [ case (key, value) of+ ("cabal", _) -> inSection at' cabalConfigKeys cabalComponentKeys value+ ("stack", _) -> inSection at' stackConfigKeys stackComponentKeys value+ ("bios", Object bios) -> unknownIn at' biosConfigKeys bios+ ("multi", Array subs) ->+ concat [ inMulti (at' ++ [Index i]) sub | (i, sub) <- zip [0 ..] (F.toList subs) ]+ _ -> []+ | (key, value) <- KM.toList o+ , let at' = at ++ [Key key]+ ]+ inCradle _ _ = []++ -- cabal and stack sections are either an object, possibly with a list of+ -- components, or just the list of components.+ inSection at sectionKeys componentKeys value = case value of+ Object o -> unknownIn at sectionKeys o+ ++ maybe [] (inComponents (at ++ [Key "components"]) componentKeys) (lookup "components" o)+ Array _ -> inComponents at componentKeys value+ _ -> []++ inComponents at componentKeys (Array cs) = concat+ [ case c of+ Object o -> unknownIn (at ++ [Index i]) componentKeys o+ _ -> []+ | (i, c) <- zip [0 ..] (F.toList cs)+ ]+ inComponents _ _ _ = []++ -- each entry of a multi cradle has its own nested configuration+ inMulti at (Object o) = maybe [] (inConfig (at ++ [Key "config"])) (lookup "config" o)+ inMulti _ _ = []++ unknownIn at allowed o = case keys o \\ allowed of+ [] -> []+ extra -> [UnknownKeys at extra allowed]+ data CradleConfigYAML a = CradleConfigYAML { cradle :: CradleComponent a , dependencies :: Maybe [FilePath]@@ -111,11 +148,10 @@ instance FromJSON CabalConfig where parseJSON v@(Array _) = CabalConfig Nothing Nothing . ManyComponents <$> parseJSON v- parseJSON v@(Object obj) = (checkObjectKeys ["cabalProject", "component", "components", "componentsToLoad"] obj)- *> (CabalConfig+ parseJSON v@(Object obj) = CabalConfig <$> obj .:? "cabalProject" <*> obj .:? "componentsToLoad"- <*> parseJSON v)+ <*> parseJSON v parseJSON Null = pure $ CabalConfig Nothing Nothing NoComponent parseJSON v = typeMismatch "CabalConfig" v @@ -127,12 +163,10 @@ instance FromJSON CabalComponent where parseJSON =- let parseCabalComponent obj = checkObjectKeys ["path", "component", "cabalProject"] obj- *> (CabalComponent- <$> obj .: "path"- <*> obj .: "component"- <*> obj .:? "cabalProject"- )+ let parseCabalComponent obj = CabalComponent+ <$> obj .: "path"+ <*> obj .: "component"+ <*> obj .:? "cabalProject" in withObject "CabalComponent" parseCabalComponent data StackConfig@@ -149,22 +183,19 @@ instance FromJSON StackConfig where parseJSON v@(Array _) = StackConfig Nothing Nothing . ManyComponents <$> parseJSON v- parseJSON v@(Object obj) = (checkObjectKeys ["component", "components", "stackYaml", "componentsToLoad"] obj)- *> (StackConfig- <$> obj .:? "stackYaml"- <*> obj .:? "componentsToLoad"- <*> parseJSON v- )+ parseJSON v@(Object obj) = StackConfig+ <$> obj .:? "stackYaml"+ <*> obj .:? "componentsToLoad"+ <*> parseJSON v parseJSON Null = pure $ StackConfig Nothing Nothing NoComponent parseJSON v = typeMismatch "StackConfig" v instance FromJSON StackComponent where parseJSON =- let parseStackComponent obj = (checkObjectKeys ["path", "component", "stackYaml"] obj)- *> (StackComponent- <$> obj .: "path"- <*> obj .: "component"- <*> obj .:? "stackYaml")+ let parseStackComponent obj = StackComponent+ <$> obj .: "path"+ <*> obj .: "component"+ <*> obj .:? "stackYaml" in withObject "StackComponent" parseStackComponent data OneOrManyComponents component@@ -203,8 +234,6 @@ parseDepsCallable o = (Just . Program <$> o .: "dependency-program") <|> (Just . Shell <$> o .: "dependency-shell") <|> (pure Nothing)- parse o = BiosConfig <$> parseCallable o- <*> parseDepsCallable o- <*> (o .:? "with-ghc")- check = checkObjectKeys ["program", "shell", "dependency-program", "dependency-shell", "with-ghc"]- in check obj *> parse obj+ in BiosConfig <$> parseCallable obj+ <*> parseDepsCallable obj+ <*> (obj .:? "with-ghc")
src/HIE/Bios/Cradle.hs view
@@ -54,7 +54,7 @@ import System.IO.Temp import HIE.Bios.Config-import HIE.Bios.Environment (resolveCacheDir)+import HIE.Bios.Environment (resolveCacheRootDir) import HIE.Bios.Types hiding (ActionName(..)) import qualified HIE.Bios.Process as Process import qualified HIE.Bios.Types as Types@@ -108,8 +108,9 @@ -- in a cabal directory. loadCradleWithOpts :: (Yaml.FromJSON b, Show a) => LogAction IO (WithSeverity Log) -> CradleRunConfig -> (b -> CradleAction a) -> FilePath -> IO (Cradle a) loadCradleWithOpts l config buildCustomCradle wfile = do- cradleConfig <- readCradleConfig wfile+ cradleConfig <- readCradleConfig l wfile l <& WithSeverity (LogAny $ T.pack $ "Cradle Config: " ++ show cradleConfig) Debug+ l <& WithSeverity (LogAny $ T.pack $ "Cradle Run Config: " ++ show config) Debug getCradleWithConfig l config buildCustomCradle (cradleConfig, takeDirectory wfile) getCradle :: Show a => LogAction IO (WithSeverity Log) -> (b -> CradleAction a) -> (CradleConfig b, FilePath) -> IO (Cradle a)@@ -119,9 +120,10 @@ getCradleWithConfig :: Show a => LogAction IO (WithSeverity Log) -> CradleRunConfig -> (b -> CradleAction a) -> (CradleConfig b, FilePath) -> IO (Cradle a) getCradleWithConfig l config buildCustomCradle (cc, wdir) = do rcs <- canonicalizeResolvedCradles wdir cs- liftIO $ l <& WithSeverity (LogAny . T.pack $ "Resolved Cradles " ++ show ((fmap . fmap) (const ()) rcs)) Debug- cacheDir <- resolveCacheDir "" (cradleCacheDir config)- resolvedCradlesToCradle l buildCustomCradle wdir cacheDir rcs+ l <& WithSeverity (LogAny . T.pack $ "Resolved Cradles " ++ show ((fmap . fmap) (const ()) rcs)) Debug+ l <& WithSeverity (LogAny $ T.pack $ "Resolved Cradles Run Config: " ++ show config) Debug+ cacheRootDir <- resolveCacheRootDir (cradleCacheRootDir config)+ resolvedCradlesToCradle l buildCustomCradle wdir cacheRootDir rcs where cs = resolveCradleTree wdir cc @@ -133,8 +135,8 @@ (\(ComponentOptions os' dir ds) -> CradleSuccess (ComponentOptions os' dir (ds `union` deps))) -resolvedCradlesToCradle :: Show a => LogAction IO (WithSeverity Log) -> (b -> CradleAction a) -> FilePath -> CacheDir -> [ResolvedCradle b] -> IO (Cradle a)-resolvedCradlesToCradle logger buildCustomCradle root cacheDir cs = mdo+resolvedCradlesToCradle :: Show a => LogAction IO (WithSeverity Log) -> (b -> CradleAction a) -> FilePath -> CacheRootDir -> [ResolvedCradle b] -> IO (Cradle a)+resolvedCradlesToCradle logger buildCustomCradle root cacheRootDir cs = mdo let run_ghc_cmd args = -- We're being lazy here and just returning the ghc path for the -- first non-none cradle. This shouldn't matter in practice: all@@ -146,7 +148,7 @@ act args versions <- makeVersions logger root run_ghc_cmd- let rcs = ResolvedCradles root cs versions cacheDir+ let rcs = ResolvedCradles root cs versions cacheRootDir cradleActions = [ (c, resolveCradleAction logger buildCustomCradle rcs root c) | c <- cs ] err_msg (TargetWithContext fp fps) = ["Multi Cradle: No prefixes matched"@@ -165,7 +167,7 @@ case selectCradle (prefix . fst) absfp cradleActions of Just (rc, act) -> do addActionDeps (cradleDeps rc) <$> runCradle act fpc prev- Nothing -> return $ CradleFail $ CradleError [] ExitSuccess (err_msg fpc) (targetFilePath fpc: targetContext fpc)+ Nothing -> return $ CradleFail $ CradleError [] (Right ExitSuccess) (err_msg fpc) (targetFilePath fpc: targetContext fpc) , runGhcCmd = run_ghc_cmd } }@@ -276,9 +278,10 @@ yamlConfigDirectory :: FilePath -> MaybeT IO FilePath yamlConfigDirectory = Process.findFileUpwards configFileName -readCradleConfig :: Yaml.FromJSON b => FilePath -> IO (CradleConfig b)-readCradleConfig yamlHie = do- cfg <- liftIO $ readConfig yamlHie+readCradleConfig :: Yaml.FromJSON b => LogAction IO (WithSeverity Log) -> FilePath -> IO (CradleConfig b)+readCradleConfig l yamlHie = do+ (warnings, cfg) <- liftIO $ readConfigWithWarnings yamlHie+ forM_ warnings $ \w -> l <& WithSeverity (LogConfigWarning yamlHie w) Warning return (cradle cfg) configFileName :: FilePath@@ -582,7 +585,7 @@ logCradleHasNoSupportForLoadFileWithContext l loadStyle "stack" let ghcProc args = proc "stack" (stackYamlProcessArgs syaml <> ["exec", "ghc", "--"] <> args) -- Same wrapper works as with cabal- wrapper_fp <- withGhcWrapperTool l (cradleCacheDirResolved cs) ghcProc workDir+ wrapper_fp <- withGhcWrapperTool l (cradleCacheRootDirResolved cs) ghcProc workDir let fallback = [ comp | Just comp <- [mc] ] componentsToLoad = nubOrd <$> mconcat@@ -621,7 +624,7 @@ -- the root of the component, so we are right in trivial cases at least. deps <- stackCradleDependencies workDir workDir syaml pure $ CradleFail- (CradleError deps ex1+ (CradleError deps (Right ex1) ([ "Failed to parse result of calling stack" ] ++ stde ++ args)@@ -731,7 +734,7 @@ makeCradleResult :: (ExitCode, [String], FilePath, [String]) -> [FilePath] -> [FilePath] -> CradleLoadResult ComponentOptions makeCradleResult (ex, err, componentDir, gopts) deps loadingFiles = case ex of- ExitFailure _ -> CradleFail (CradleError deps ex err loadingFiles)+ ExitFailure _ -> CradleFail (CradleError deps (Right ex) err loadingFiles) _ -> let compOpts = ComponentOptions gopts componentDir deps in CradleSuccess compOpts
src/HIE/Bios/Cradle/Cabal.hs view
@@ -170,7 +170,7 @@ let errorMsg = "Failed to run " <> cmd <> " in directory \"" <> workDir <> "\". Consult the logs for full command and error." throwCE CradleError { cradleErrorDependencies = nubOrd (deps <> extraDeps)- , cradleErrorExitCode = ExitFailure code+ , cradleErrorExitCode = Right $ ExitFailure code , cradleErrorStderr = [errorMsg] <> prettyProcessErrorDetails errorDetails , cradleErrorLoadingFiles = loadingFiles }@@ -183,7 +183,7 @@ deps <- liftIO $ cabalCradleDependencies projectFile workDir workDir throwCE CradleError { cradleErrorDependencies = nubOrd (deps <> extraDeps)- , cradleErrorExitCode = ExitSuccess+ , cradleErrorExitCode = Right ExitSuccess , cradleErrorStderr = ["Failed to parse result of calling cabal"] <> prettyProcessErrorDetails errorDetails , cradleErrorLoadingFiles = loadingFiles }@@ -220,15 +220,15 @@ runCabalToGetGhcOptions progVersions cabalArgs = do cabalFeatures <- determineCabalLoadFeature progVersions let- cacheDir = cradleCacheDirResolved cradles+ cacheRootDir = cradleCacheRootDirResolved cradles -- The preferred way of loading ghc-options. Requires cabal 3.16- cabalWithReplProc = cabalLoadFilesWithRepl l cacheDir projectFile workDir cabalArgs+ cabalWithReplProc = cabalLoadFilesWithRepl l cacheRootDir projectFile workDir cabalArgs -- Legacy way of loading ghc-options. -- Supports multi-repl and the deprecated single file mode.- cabalWithGhcShimWrapper = cabalLoadFilesBefore315 l cacheDir progVersions projectFile workDir cabalArgs+ cabalWithGhcShimWrapper = cabalLoadFilesBefore315 l cacheRootDir progVersions projectFile workDir cabalArgs -- Legacy way of loading ghc-options. -- This should only be used for project with Custom setups that are older than lib:Cabal 3.16.- cabalWithGhcShimWrapperSingleTarget = cabalLoadFilesBefore315 l cacheDir progVersions projectFile workDir (demoteToSingleLoadModeTarget cabalArgs)+ cabalWithGhcShimWrapperSingleTarget = cabalLoadFilesBefore315 l cacheRootDir progVersions projectFile workDir (demoteToSingleLoadModeTarget cabalArgs) cabalProc <- case cabalFeatures of CabalWithRepl -> cabalWithReplProc@@ -284,15 +284,15 @@ runCabalGhcCmd :: ResolvedCradles a -> FilePath -> LogAction IO (WithSeverity Log) -> CradleProjectConfig -> [String] -> IO (CradleLoadResult String) runCabalGhcCmd cs wdir l projectFile args = runCradleResultT $ do let vs = cradleProgramVersions cs- callCabalPathForCompilerPath l (cradleCacheDirResolved cs) vs wdir projectFile >>= \case+ callCabalPathForCompilerPath l (cradleCacheRootDirResolved cs) vs wdir projectFile >>= \case Just p -> Process.readProcessWithCwd_ l wdir p args "" Nothing -> do- buildDir <- liftIO $ cabalBuildDir (cradleCacheDirResolved cs) wdir+ CacheDir buildDir <- liftIO $ cabalBuildDir (cradleCacheRootDirResolved cs) wdir -- Workaround for a cabal-install bug on 3.0.0.0: -- ./dist-newstyle/tmp/environment.-24811: createDirectory: does not exist (No such file or directory) liftIO $ createDirectoryIfMissing True (buildDir </> "tmp") -- Need to pass -v0 otherwise we get "resolving dependencies..."- cabalProc <- cabalExecGhc l (cradleCacheDirResolved cs) vs projectFile wdir args+ cabalProc <- cabalExecGhc l (cradleCacheRootDirResolved cs) vs projectFile wdir args Process.readProcessWithCwd' l cabalProc "" processCabalLoadMode :: MonadIO m => LogAction IO (WithSeverity Log) -> ResolvedCradles a -> ProgramVersions -> CradleProjectConfig -> [Char] -> Maybe FilePath -> TargetWithContext -> LoadMode -> m (LoadModeTargets, [FilePath], [FilePath])@@ -396,9 +396,9 @@ pure (MultipleTargets fpModule (withExtraTargets extraModules) extraComponents usesResponseFiles, fp:allFiles, mergedDeps) -cabalLoadFilesWithRepl :: LogAction IO (WithSeverity Log) -> CacheDir -> CradleProjectConfig -> FilePath -> LoadModeTargets -> CradleLoadResultT IO CreateProcess+cabalLoadFilesWithRepl :: LogAction IO (WithSeverity Log) -> CacheRootDir -> CradleProjectConfig -> FilePath -> LoadModeTargets -> CradleLoadResultT IO CreateProcess cabalLoadFilesWithRepl l cacheDir projectFile workDir args = do- buildDir <- liftIO $ cabalBuildDir cacheDir workDir+ CacheDir buildDir <- liftIO $ cabalBuildDir cacheDir workDir newEnvironment <- liftIO Process.getCleanEnvironment wrapper_fp <- liftIO $ withReplWrapperTool l cacheDir (proc "ghc") workDir let@@ -486,7 +486,7 @@ -- them. -- ---------------------------------------------------------------------------- -cabalLoadFilesBefore315 :: LogAction IO (WithSeverity Log) -> CacheDir -> ProgramVersions -> CradleProjectConfig -> [Char] -> LoadModeTargets -> CradleLoadResultT IO CreateProcess+cabalLoadFilesBefore315 :: LogAction IO (WithSeverity Log) -> CacheRootDir -> ProgramVersions -> CradleProjectConfig -> [Char] -> LoadModeTargets -> CradleLoadResultT IO CreateProcess cabalLoadFilesBefore315 l cacheDir progVersions projectFile workDir args = do let cabalCommand = "v2-repl" cabalProcess l cacheDir progVersions projectFile workDir cabalCommand (renderLoadModeTargets CabalWithGhcShimWrapper args) `modCradleError` \err -> do@@ -502,7 +502,7 @@ -- to the custom ghc wrapper via 'hie_bios_ghc' environment variable which -- the custom ghc wrapper may use as a fallback if it can not respond to certain -- queries, such as ghc version or location of the libdir.-cabalProcess :: LogAction IO (WithSeverity Log) -> CacheDir -> ProgramVersions -> CradleProjectConfig -> FilePath -> String -> [String] -> CradleLoadResultT IO CreateProcess+cabalProcess :: LogAction IO (WithSeverity Log) -> CacheRootDir -> ProgramVersions -> CradleProjectConfig -> FilePath -> String -> [String] -> CradleLoadResultT IO CreateProcess cabalProcess l cacheDir vs cabalProject workDir command args = do ghcDirs@(ghcBin, libdir) <- callCabalPathForCompilerPath l cacheDir vs workDir cabalProject >>= \case Just p -> do@@ -530,7 +530,7 @@ setupCabalCommand :: FilePath -> IO CreateProcess setupCabalCommand ghcPkgPath = do wrapper_fp <- withGhcWrapperTool l cacheDir (proc "ghc") workDir- buildDir <- cabalBuildDir cacheDir workDir+ CacheDir buildDir <- cabalBuildDir cacheDir workDir let extraCabalArgs = [ "--builddir=" <> buildDir , command@@ -589,8 +589,8 @@ -- -- Here, we restore the wrapper-shims, if necessary, thus the returned filepath -- can be passed to 'cabal' without further modifications.-withGhcPkgTool :: CacheDir -> FilePath -> FilePath -> IO FilePath-withGhcPkgTool cacheDir ghcPathAbs libdir = do+withGhcPkgTool :: CacheRootDir -> FilePath -> FilePath -> IO FilePath+withGhcPkgTool cacheRootDir ghcPathAbs libdir = do let ghcName = takeFileName ghcPathAbs -- TODO: check for existence ghcPkgPath = guessGhcPkgFromGhc ghcName@@ -626,7 +626,8 @@ ] ] srcHash = show (fingerprintString contents)- cacheFileIn cacheDir "ghc-pkg" srcHash $ \wrapperFp -> writeFile wrapperFp contents+ -- Cache the `ghc-pkg` wrapper in the `$XDG_CACHE_HOME/hie-bios`+ cacheFileIn (CacheDir $ unCacheRootDir cacheRootDir) "ghc-pkg" srcHash $ \wrapperFp -> writeFile wrapperFp contents -- Escape the filepath and trim excess newlines added by 'escapeArgs' escapeFilePath fp = trimEnd $ escapeArgs [fp]@@ -641,9 +642,9 @@ -- | Generate a fake GHC that can be passed to cabal or stack -- when run with --interactive, it will print out its -- command-line arguments and exit-withGhcWrapperTool :: LogAction IO (WithSeverity Log) -> CacheDir -> GhcProc -> FilePath -> IO FilePath-withGhcWrapperTool l cacheDir mkGhcCall wdir = do- withWrapperTool l cacheDir mkGhcCall wdir "wrapper" cabalWrapperHs cabalWrapper+withGhcWrapperTool :: LogAction IO (WithSeverity Log) -> CacheRootDir -> GhcProc -> FilePath -> IO FilePath+withGhcWrapperTool l cacheRootDir mkGhcCall wdir = do+ withWrapperTool l cacheRootDir mkGhcCall wdir "wrapper" cabalWrapperHs cabalWrapper -- | Generate a script/binary that can be passed to cabal's '--with-repl'. -- On windows, this compiles a Haskell file, while on other systems, we persist@@ -651,16 +652,17 @@ -- -- 'GhcProc' is unused on other platforms. ---withReplWrapperTool :: LogAction IO (WithSeverity Log) -> CacheDir -> GhcProc -> FilePath -> IO FilePath+withReplWrapperTool :: LogAction IO (WithSeverity Log) -> CacheRootDir -> GhcProc -> FilePath -> IO FilePath withReplWrapperTool l cacheDir mkGhcCall wdir = withWrapperTool l cacheDir mkGhcCall wdir "repl-wrapper" cabalWithReplWrapperHs cabalWithReplWrapper -withWrapperTool :: LogAction IO (WithSeverity Log) -> CacheDir -> GhcProc -> String -> FilePath -> String -> String -> IO FilePath-withWrapperTool l cacheDir mkGhcCall wdir baseName windowsWrapper unixWrapper = do+withWrapperTool :: LogAction IO (WithSeverity Log) -> CacheRootDir -> GhcProc -> String -> FilePath -> String -> String -> IO FilePath+withWrapperTool l cacheRootDir mkGhcCall wdir baseName windowsWrapper unixWrapper = do let wrapperContents = if isWindows then windowsWrapper else unixWrapper withExtension fp = if isWindows then fp <.> "exe" else fp srcHash = show (fingerprintString wrapperContents)- cacheFileIn cacheDir (withExtension baseName) srcHash $ \wrapper_fp ->+ -- The wrapper tool is cached in `$XDG_CACHE_HOME/hie-bios`, no sub directory+ cacheFileIn (CacheDir $ unCacheRootDir cacheRootDir) (withExtension baseName) srcHash $ \wrapper_fp -> if isWindows then withSystemTempDirectory "hie-bios" $ \ tmpDir -> do@@ -672,7 +674,7 @@ } l <& LogCreateProcessRun ghcProc `WithSeverity` Debug readCreateProcess ghcProc "" >>= putStr- else writeFile wrapper_fp wrapperContents+ else writeFileNoInherit wrapper_fp wrapperContents -- ---------------------------------------------------------------------------- -- 'cabal.project' options@@ -693,11 +695,11 @@ -- | Given the cache root and the work directory, get the build dir we are -- using for cabal.-cabalBuildDir :: CacheDir -> FilePath -> IO FilePath-cabalBuildDir (CacheDir cacheDir) workDir = do+cabalBuildDir :: CacheRootDir -> FilePath -> IO CacheDir+cabalBuildDir (CacheRootDir cacheDir) workDir = do abs_work_dir <- makeAbsolute workDir let dirHash = show (fingerprintString abs_work_dir)- pure $ cacheDir </> ("dist-" <> filter (not . isSpace) (takeBaseName abs_work_dir)<>"-"<>dirHash)+ pure $ CacheDir $ cacheDir </> ("dist-" <> filter (not . isSpace) (takeBaseName abs_work_dir) <> "-" <> dirHash) -- |Find .cabal files in the given directory. --@@ -712,16 +714,16 @@ -- cabal process wrappers and helpers -- ---------------------------------------------------------------------------- -cabalExecGhc :: LogAction IO (WithSeverity Log) -> CacheDir -> ProgramVersions -> CradleProjectConfig -> FilePath -> [String] -> CradleLoadResultT IO CreateProcess-cabalExecGhc l cacheDir vs projectFile wdir args = do- cabalProcess l cacheDir vs projectFile wdir "v2-exec" $ ["ghc", "-v0", "--"] ++ args+cabalExecGhc :: LogAction IO (WithSeverity Log) -> CacheRootDir -> ProgramVersions -> CradleProjectConfig -> FilePath -> [String] -> CradleLoadResultT IO CreateProcess+cabalExecGhc l cacheRootDir vs projectFile wdir args = do+ cabalProcess l cacheRootDir vs projectFile wdir "v2-exec" $ ["ghc", "-v0", "--"] ++ args -callCabalPathForCompilerPath :: LogAction IO (WithSeverity Log) -> CacheDir -> ProgramVersions -> FilePath -> CradleProjectConfig -> CradleLoadResultT IO (Maybe FilePath)+callCabalPathForCompilerPath :: LogAction IO (WithSeverity Log) -> CacheRootDir -> ProgramVersions -> FilePath -> CradleProjectConfig -> CradleLoadResultT IO (Maybe FilePath) callCabalPathForCompilerPath l cacheDir vs workDir projectFile = do isCabalPathSupported vs >>= \case False -> pure Nothing True -> do- buildDir <- liftIO $ cabalBuildDir cacheDir workDir+ CacheDir buildDir <- liftIO $ cabalBuildDir cacheDir workDir let args = [ "--builddir=" <> buildDir, "path", "--output-format=json" ] <> projectFileProcessArgs projectFile
src/HIE/Bios/Cradle/Resolved.hs view
@@ -15,7 +15,7 @@ { cradleRoot :: FilePath , resolvedCradles :: [ResolvedCradle a] -- ^ In order of decreasing specificity , cradleProgramVersions :: ProgramVersions- , cradleCacheDirResolved :: CacheDir+ , cradleCacheRootDirResolved :: CacheRootDir } -- | 'ConcreteCradle' augmented with information on which file the
src/HIE/Bios/Environment.hs view
@@ -1,35 +1,45 @@ {-# LANGUAGE RecordWildCards, CPP #-} {-# LANGUAGE TupleSections #-}-module HIE.Bios.Environment (initSession, initSession', getRuntimeGhcLibDir, getRuntimeGhcVersion, makeDynFlagsAbsolute, makeTargetsAbsolute, getCacheDir, resolveCacheDir, addCmdOpts, extractUnits) where+module HIE.Bios.Environment (+ initSession,+ initSession',+ getRuntimeGhcLibDir,+ getRuntimeGhcVersion,+ makeDynFlagsAbsolute,+ makeTargetsAbsolute,+ resolveCacheRootDir,+ resolveCacheDirIn,+ addCmdOpts,+ extractUnits,+) where import GHC (GhcMonad) import qualified GHC as G+import GHC.Driver.Env (HscEnv (hsc_unit_env))+import qualified GHC.Driver.Monad as G +import qualified GHC.Plugins as G+import qualified GHC.Unit.Env as G+import qualified HIE.Bios.Ghc.Gap as Gap+import HIE.Bios.Types+ import Control.Applicative import Control.Monad (void) import Control.Monad.IO.Class--import System.Directory-import System.FilePath-import System.Environment (lookupEnv)- import qualified Crypto.Hash.SHA1 as H-import qualified Data.ByteString.Char8 as B import Data.ByteString.Base16-import Data.List import Data.Char (isSpace)-import Text.ParserCombinators.ReadP hiding (optional)--import HIE.Bios.Types-import qualified HIE.Bios.Ghc.Gap as Gap-import qualified System.OsPath as OsPath-import qualified GHC.Plugins as G-import qualified Data.List.NonEmpty as NE-import qualified GHC.Driver.Monad as G import Data.IORef (newIORef, readIORef)-import qualified GHC.Unit.Env as G-import GHC.Driver.Env (HscEnv(hsc_unit_env))+import Data.List+import qualified Data.List.NonEmpty as NE import Data.Maybe (fromMaybe)+import qualified Data.Text as Text+import qualified Data.Text.Encoding as Text.Encoding+import System.Directory+import System.Environment (lookupEnv)+import System.FilePath+import qualified System.OsPath as OsPath+import Text.ParserCombinators.ReadP hiding (optional) -- | Start a GHC session and set some sensible options for tooling to use. -- Creates a folder in the cache directory to cache interface files to make@@ -42,15 +52,15 @@ -- | 'initSession' with caches placed under the given root instead of resolved -- from the environment. initSession' :: (GhcMonad m)- => Maybe CacheDir+ => Maybe CacheRootDir -> ComponentOptions -> m [G.Target] initSession' mCacheRoot ComponentOptions {..} = do -- Create a unique folder per set of different GHC options, assuming that each different set of -- GHC options will create incompatible interface files.- let opts_hash = B.unpack $ encode $ H.finalize $ H.updates H.init $ map B.pack componentOptions+ let opts_hash = Text.unpack $ Text.Encoding.decodeUtf8 $ encode $ H.finalize $ H.updates H.init $ map (Text.Encoding.encodeUtf8 . Text.pack) componentOptions - cache_dir <- liftIO $ resolveCacheDir opts_hash mCacheRoot+ cache_dir <- liftIO $ resolveCacheDirIn opts_hash mCacheRoot -- Plan: -- - Extract `-unit @resp_file` options if present@@ -150,37 +160,30 @@ cacheDir :: String cacheDir = "hie-bios" -{- |-Back in the day we used to clear the cache at the start of each session,-however, it's not really necessary as-1. There is one cache dir for any change in options.-2. Interface files are resistent to bad option changes anyway.--> clearInterfaceCache :: FilePath -> IO ()-> clearInterfaceCache fp = do-> cd <- getCacheDir fp-> res <- doesPathExist cd-> when res (removeDirectoryRecursive cd)--}---- | Prepends the cache directory used by the library to the supplied file path.--- It tries to use the path under the environment variable `$HIE_BIOS_CACHE_DIR`--- and falls back to the standard `$XDG_CACHE_HOME/hie-bios` if the former is not set-getCacheDir :: FilePath -> IO CacheDir-getCacheDir fp = do+-- | Resolve a cache directory root, appending @suffix@ and making it absolute.+--+-- The cache root is determined as follows:+--+-- 1. Check @HIE_BIOS_CACHE_DIR@ environment variable+-- 2. Check 'Maybe CacheRootDir' and use it if given+-- 3. Use @$XDG_CACHE_HOME/hie-bios@ as the cache location.+resolveCacheRootDir :: Maybe CacheRootDir -> IO CacheRootDir+resolveCacheRootDir mCacheRoot = do mbEnvCacheDirectory <- lookupEnv "HIE_BIOS_CACHE_DIR"- cacheBaseDir <- maybe (getXdgDirectory XdgCache cacheDir) return- mbEnvCacheDirectory- return (CacheDir (cacheBaseDir </> fp))+ cacheBaseDir <-+ case mbEnvCacheDirectory of+ Just root -> pure root+ Nothing -> case mCacheRoot of+ Just (CacheRootDir root) -> pure root+ Nothing -> getXdgDirectory XdgCache cacheDir --- | Resolve a cache directory root, appending @suffix@ and making it absolute.--- An explicit path is used as given. 'Nothing' falls back to 'getCacheDir'.-resolveCacheDir :: FilePath -> Maybe CacheDir -> IO CacheDir-resolveCacheDir suffix mCacheRoot = do- resolved <- case mCacheRoot of- Nothing -> fmap unCacheDir (getCacheDir suffix)- Just cacheRoot -> pure ((</> suffix) (unCacheDir cacheRoot))- fmap CacheDir (makeAbsolute resolved)+ pure (CacheRootDir cacheBaseDir)++-- | Like 'resolveCacheRootDir' but appends the given 'FilePath' to the 'CacheDir'.+resolveCacheDirIn :: FilePath -> Maybe CacheRootDir -> IO CacheDir+resolveCacheDirIn suffix mCacheRoot = do+ CacheRootDir baseDir <- resolveCacheRootDir mCacheRoot+ pure $ CacheDir (baseDir </> suffix) ----------------------------------------------------------------
src/HIE/Bios/Flags.hs view
@@ -6,8 +6,8 @@ -- | Initialize the 'DynFlags' relating to the compilation of a single -- file or GHC session according to the provided 'Cradle'.---- | Note: @getCompilerOptions (TargetWithContext path cxt) LoadFile@ will warn if `cxt` is non-empty.+--+-- Note: @'getCompilerOptions' (TargetWithContext path cxt) LoadFile@ will warn if `cxt` is non-empty. getCompilerOptions :: TargetWithContext -> LoadMode -> Cradle a -> IO (CradleLoadResult ComponentOptions) getCompilerOptions target loadMode cradle = do (cradleLogger cradle) <& LogProcessOutput "invoking build tool to determine build flags (this may take some time depending on the cache)" `WithSeverity` Info
src/HIE/Bios/Ghc/Api.hs view
@@ -54,7 +54,7 @@ -- | 'initSessionWithMessage' with the interface-file cache placed under the -- given root, see 'initSession''. initSessionWithMessage' :: (GhcMonad m)- => Maybe CacheDir+ => Maybe CacheRootDir -> Maybe G.Messager -> ComponentOptions -> (m G.SuccessFlag, ComponentOptions)
src/HIE/Bios/Ghc/Gap.hs view
@@ -173,7 +173,7 @@ overPkgDbRef :: (OsPath -> OsPath) -> G.PackageDBFlag -> G.PackageDBFlag overPkgDbRef f (G.PackageDB pkgConfRef) = G.PackageDB $ case pkgConfRef of G.PkgDbPath fp ->-#if __GLASGOW_HASKELL__ >= 915+#if MIN_VERSION_GLASGOW_HASKELL(9, 14, 1, 20260728) G.PkgDbPath (f fp) #else G.PkgDbPath (unsafeDecodeUtf $ f $ unsafeEncodeUtf fp)
src/HIE/Bios/Ghc/Logger.hs view
@@ -1,4 +1,9 @@ {-# LANGUAGE BangPatterns, CPP, TypeApplications #-}+#if __GLASGOW_HASKELL__ >= 1001+{-# OPTIONS_GHC -Wno-x-internalDebugPprMsgEnvelope #-}+ -- We don't care about e.g. -ddump-json, so we don't need to go through 'printMessage'.+ -- Use the internal function to render message to SDoc directly+#endif module HIE.Bios.Ghc.Logger ( withLogger@@ -96,7 +101,9 @@ ppErrMsg dflag style err = ppMsg spn SevError dflag style msg -- ++ ext where spn = errMsgSpan err-#if __GLASGOW_HASKELL__ >= 905+#if __GLASGOW_HASKELL__ >= 1001+ msg = internalDebugPprMsgEnvelope @GhcMessage err+#elif __GLASGOW_HASKELL__ >= 905 msg = pprLocMsgEnvelope (defaultDiagnosticOpts @GhcMessage) err #else msg = pprLocMsgEnvelope err
src/HIE/Bios/Process.hs view
@@ -1,6 +1,7 @@ {-# LANGUAGE BangPatterns #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE CPP #-} module HIE.Bios.Process ( CreateProcess(..) -- * Run processes with extra environment variables@@ -10,8 +11,8 @@ , readProcessWithOutputs , getCleanEnvironment -- * File Caching- , cacheFile , cacheFileIn+ , writeFileNoInherit -- * Find file utilities , findFileUpwards , findFileUpwardsPredicate@@ -19,9 +20,8 @@ ) where -import Control.Applicative (optional) import Control.DeepSeq-import Control.Exception (handleJust)+import qualified Control.Exception as Exc import System.Exit import System.Directory hiding (findFile) import Colog.Core (LogAction (..), WithSeverity (..), Severity (..), (<&))@@ -39,45 +39,56 @@ import System.Environment import System.FileLock import System.FilePath-import System.IO (hClose, hGetContents, hSetBuffering, BufferMode(LineBuffering), withFile, IOMode(..))+import System.IO import System.IO.Error (isPermissionError) import System.IO.Temp import HIE.Bios.Types import Control.Monad.Extra (unlessM) import System.PosixCompat (setFileMode, accessModes)-import HIE.Bios.Environment (getCacheDir) +#ifndef mingw32_HOST_OS+import System.Posix.IO (+ OpenFileFlags (..),+ OpenMode (..),+ defaultFileFlags,+ fdToHandle,+ openFd,+ )+import System.PosixCompat (stdFileMode)+#endif+ -- | Wrapper around 'readCreateProcess' that sets the working directory and -- clears the environment, suitable for invoking cabal/stack and raw ghc commands. readProcessWithCwd :: LogAction IO (WithSeverity Log) -> FilePath -> FilePath -> [String] -> String -> IO (CradleLoadResult String)-readProcessWithCwd l dir cmd args stdin = runCradleResultT $ readProcessWithCwd_ l dir cmd args stdin+readProcessWithCwd l dir cmd args stdinH = runCradleResultT $ readProcessWithCwd_ l dir cmd args stdinH readProcessWithCwd_ :: LogAction IO (WithSeverity Log) -> FilePath -> FilePath -> [String] -> String -> CradleLoadResultT IO String-readProcessWithCwd_ l dir cmd args stdin = do+readProcessWithCwd_ l dir cmd args stdinH = do cleanEnv <- liftIO getCleanEnvironment let createdProc' = (proc cmd args) { cwd = Just dir, env = Just cleanEnv }- readProcessWithCwd' l createdProc' stdin+ readProcessWithCwd' l createdProc' stdinH -- | Wrapper around 'readCreateProcessWithExitCode', wrapping the result in -- a 'CradleLoadResult'. Provides better error messages than raw 'readCreateProcess'. readProcessWithCwd' :: LogAction IO (WithSeverity Log) -> CreateProcess -> String -> CradleLoadResultT IO String-readProcessWithCwd' l createdProcess stdin = do- mResult <- liftIO $ optional $ readCreateProcessWithExitCode createdProcess stdin+readProcessWithCwd' l createdProcess stdinH = do+ eResult <- liftIO $ Exc.try $ readCreateProcessWithExitCode createdProcess stdinH liftIO $ l <& LogCreateProcessRun createdProcess `WithSeverity` Debug let cmdString = prettyCmdSpec $ cmdspec createdProcess- case mResult of- Just (ExitSuccess, stdo, _) -> pure stdo- Just (exitCode, stdo, stde) -> throwCE $- CradleError [] exitCode+ case eResult of+ Right (ExitSuccess, stdo, _) -> pure stdo+ Right (exitCode, stdo, stde) -> throwCE $+ CradleError [] (Right exitCode) (["Error when calling " <> cmdString, stdo, stde] <> prettyProcessEnv createdProcess) []- Nothing -> throwCE $- CradleError [] ExitSuccess- (["Couldn't execute " <> cmdString] <> prettyProcessEnv createdProcess)+ Left e -> throwCE $+ CradleError [] (Left e)+ (["Couldn't execute " <> cmdString] <> [Exc.displayException e] <> prettyProcessEnv createdProcess) [] + -- | Some environments (e.g. stack exec) include GHC_PACKAGE_PATH. -- Cabal v2 *will* complain, even though or precisely because it ignores them. -- Unset them from the environment to sidestep this@@ -144,7 +155,7 @@ -- | Create and cache a file in hie-bios's cache directory. ----- @'cacheFile' fpName srcHash populate@. 'fpName' is the pattern name of the+-- @'cacheFileIn' cacheDir fpName srcHash populate@. 'fpName' is the pattern name of the -- cached file you want to create. 'srcHash' is the hash that is appended to -- the file pattern and is expected to change whenever you want to invalidate -- the cache.@@ -155,13 +166,6 @@ -- If the file does not exist yet, 'populate' is invoked with cached file -- location and it is expected that the caller persists the given filepath in -- the File System.-cacheFile :: FilePath -> String -> (FilePath -> IO ()) -> IO FilePath-cacheFile fpName srcHash populate = do- cacheDir <- getCacheDir ""- cacheFileIn cacheDir fpName srcHash populate---- | 'cacheFile' with the cache directory given explicitly instead of resolved--- from the environment. cacheFileIn :: CacheDir -> FilePath -> String -> (FilePath -> IO ()) -> IO FilePath cacheFileIn (CacheDir cacheDir) fpName srcHash populate = do createDirectoryIfMissing True cacheDir@@ -177,6 +181,31 @@ renamePath tmpFile newFpName pure newFpName +-- | Write a file with the given contents, opening the file handle with @closexec = True@.+--+-- This avoids a nasty race where the fd is inherited by multiple parallel tests and then one+-- test tries to exec that fd, which fails because the fd might be inherited by other long running+-- processes.+--+-- We make sure that the fd is closed when it is being exec'd, which fixes the race in our test.+-- In HLS, hie-bios is always only called single threaded, so this should have no effect, and is purely+-- for our tests.+writeFileNoInherit :: FilePath -> String -> IO ()+writeFileNoInherit fp contents =+#ifdef mingw32_HOST_OS+ writeFile fp contents+#else+ Exc.bracket open hClose (\h -> hPutStr h contents)+ where+ open = do+ fd <- openFd fp WriteOnly defaultFileFlags+ { creat = Just stdFileMode+ , trunc = True+ , cloexec = True+ }+ fdToHandle fd+#endif+ ------------------------------------------------------------------------------ -- Utilities @@ -186,7 +215,7 @@ findFileUpwards filename dir = do cnts <- liftIO- $ handleJust+ $ Exc.handleJust -- Catch permission errors (\(e :: IOError) -> if isPermissionError e then Just False else Nothing) pure@@ -206,7 +235,7 @@ findFileUpwardsPredicate p dir = do cnts <- liftIO- $ handleJust+ $ Exc.handleJust -- Catch permission errors (\(e :: IOError) -> if isPermissionError e then Just [] else Nothing) pure
src/HIE/Bios/Types.hs view
@@ -15,12 +15,16 @@ #if MIN_VERSION_base(4,9,0) import qualified Control.Monad.Fail as Fail #endif+import qualified Data.Aeson.Key as Key+import Data.Aeson.Types (formatPath) import Data.Maybe (fromMaybe) import Data.String import qualified Data.Text as T import Prettyprinter import System.Process.Extra (CreateProcess (env, cmdspec), CmdSpec (..), showCommandForUser) +import HIE.Bios.Config.YAML (ConfigWarning (..))+ ---------------------------------------------------------------- -- Environment variables used by hie-bios. --@@ -112,6 +116,8 @@ | LogWithReplNotSupported [String] | LogKeepTempFilesNotSupported [String] | LogCabalPath !T.Text+ | LogConfigWarning FilePath ConfigWarning+ -- ^ Something in a @hie.yaml@ file was ignored. deriving (Show) instance Pretty LoadMode where@@ -173,6 +179,14 @@ pretty (LogCabalPath err) = "Could not parse json output of 'cabal path': " <> line <> indent 4 (pretty err)+ pretty (LogConfigWarning file (UnknownKeys path unknown known)) =+ pretty file <> ":" <+> "ignoring unknown"+ <+> plural "key" "keys" (length unknown)+ <+> quotedList unknown+ <+> "in" <+> pretty (formatPath path) <> "."+ <+> "The keys understood there are" <+> quotedList known <> "."+ where+ quotedList = hsep . punctuate comma . map (dquotes . pretty . Key.toText) type Component = String @@ -211,20 +225,26 @@ | LoadUnitsFromCradle deriving (Eq,Ord,Enum,Bounded,Show) +-- | Root directory of the hie-bios cache hierarchy.+newtype CacheRootDir = CacheRootDir { unCacheRootDir :: FilePath }+ deriving (Show, Eq)+ deriving newtype (IsString)++-- | A cache directory for a specific tool output, e.g. cabal. newtype CacheDir = CacheDir { unCacheDir :: FilePath } deriving (Show, Eq) deriving newtype (IsString) -- | Configuration for constructing and running a 'Cradle'. data CradleRunConfig = CradleRunConfig- { cradleCacheDir :: Maybe CacheDir+ { cradleCacheRootDir :: Maybe CacheRootDir -- ^ Root directory for cache artefacts produced while running the cradle.- -- 'Nothing' falls back to @$HIE_BIOS_CACHE_DIR@, or the XDG cache+ -- 'Nothing' falls back to @$HIE_BIOS_CACHE_DIR/hie-bios@, or the XDG cache -- directory if that is unset. See 'resolveCacheDir'. } deriving (Show, Eq) defaultCradleRunConfig :: CradleRunConfig-defaultCradleRunConfig = CradleRunConfig { cradleCacheDir = Nothing }+defaultCradleRunConfig = CradleRunConfig { cradleCacheRootDir = Nothing } data CradleAction a = CradleAction { actionName :: ActionName a@@ -332,7 +352,7 @@ { cradleErrorDependencies :: [FilePath] -- ^ Dependencies of the cradle that failed to load. -- Can be watched for changes to attempt a reload of the cradle.- , cradleErrorExitCode :: ExitCode+ , cradleErrorExitCode :: Either IOError ExitCode -- ^ ExitCode of the cradle loading mechanism. , cradleErrorStderr :: [String] -- ^ Standard error output that can be shown to users to explain
tests/BiosTests.hs view
@@ -15,34 +15,32 @@ import Control.Monad (forM, forM_, unless, when) import Control.Monad.Extra (unlessM) import Control.Monad.IO.Class+import Data.Bifunctor import Data.Foldable (for_)-import Data.List (isInfixOf, isPrefixOf, sort, tails, last)+import Data.List (isInfixOf, isPrefixOf, sort, tails) import Data.Maybe (isJust)-import Data.Typeable import Data.Version import HIE.Bios import HIE.Bios.Cradle import HIE.Bios.Cradle.Cabal (cabalBuildDir) import HIE.Bios.Cradle.Utils (expandGhcOptionResponseFile)-import HIE.Bios.Environment (extractUnits, resolveCacheDir)+import HIE.Bios.Environment (extractUnits) import qualified HIE.Bios.Ghc.Gap as Gap import HIE.Bios.Process (cacheFileIn)-import HIE.Bios.Types (CacheDir (..), LoadMode (..), TargetWithContext (..))+import HIE.Bios.Types (CacheDir (..), CacheRootDir (..), LoadMode (..), TargetWithContext (..)) import System.Directory-import System.Exit (ExitCode (ExitFailure, ExitSuccess))+import System.Exit (ExitCode (ExitFailure)) import System.FilePath (makeRelative, (</>)) import System.IO (BufferMode (LineBuffering), hSetBuffering, stderr, stdout)+import System.IO.Error (ioeGetErrorType) import System.IO.Temp import System.Info.Extra (isWindows) import System.Process import Test.Tasty import Test.Tasty.ExpectedFailure import Test.Tasty.HUnit-import qualified Test.Tasty.Ingredients as Tasty-import qualified Test.Tasty.Options as Tasty import qualified Test.Tasty.Runners as Tasty import Text.ParserCombinators.ReadP (readP_to_S)-import Debug.Trace (traceShowId) argDynamic :: [String] argDynamic = ["-dynamic" | Gap.hostIsDynamic]@@ -83,7 +81,7 @@ -- race to initialise it and can fail with "package.db already exists". when (toolExists cabalDep && toolExists extraGhcDep) warmupExtraGhcStore - defaultMainWithIngredients (ignoreToolTests:verboseLogging:defaultIngredients) $+ defaultMainWithIngredients (ignoreToolTests:verboseLogging:keepTempFiles:defaultIngredients) $ -- Run tests sequentially on Windows, to avoid issues with locking of the -- package database, e.g. errors of the form: -- package.db/package.cache.lock: openBinaryFile: resource busy (file is locked)@@ -177,7 +175,7 @@ assertCradle isBiosCradle loadComponentOptions $ TargetWithContext "B.hs" [] assertCradleError $ \CradleError {..} -> do- cradleErrorExitCode @?= ExitFailure 1+ cradleErrorExitCode @?= Right (ExitFailure 1) cradleErrorDependencies `shouldMatchList` ["hie.yaml"] , biosTestCase "failing-bios-ghc" $ runTestEnv "./failing-bios-ghc" $ do initCradle "B.hs"@@ -185,14 +183,16 @@ loadRuntimeGhcVersion ghcVersionLR <- askGhcVersionResult assertCradleLoadError ghcVersionLR >>= \CradleError {..} -> liftIO $ do- cradleErrorExitCode @?= ExitSuccess+ -- on macOS, ghc 9.6.7 we get OtherError that prints as "failed" and doesn't have an exported name.+ bimap ((`elem` ["failed","does not exist"]) . show . ioeGetErrorType) id cradleErrorExitCode @?= Left True cradleErrorDependencies `shouldMatchList` []- length cradleErrorStderr @?= 1- forM_ cradleErrorStderr $ \errorCtx ->- -- On windows, this error message contains '"' around the executable name- if isWindows- then "Couldn't execute \"myGhc\"" `isPrefixOf` errorCtx @? "Error message should contain error information"- else "Couldn't execute myGhc" `isPrefixOf` errorCtx @? "Error message should contain error information"+ length cradleErrorStderr @?= 2+ let errorCtx = unlines cradleErrorStderr+ -- On windows, this error message contains '"' around the executable name+ if isWindows+ then "Couldn't execute \"myGhc\"" `isPrefixOf` errorCtx @? ("Error message should contain error information:\n" ++ errorCtx)+ else "Couldn't execute myGhc" `isPrefixOf` errorCtx @? ("Error message should contain error information:\n" ++ errorCtx)+ either show show cradleErrorExitCode `isInfixOf` errorCtx @? ("Error message should display the exception:\n" ++ errorCtx) , biosTestCase "simple-bios-shell" $ runTestEnv "./simple-bios-shell" $ do testDirectoryM isBiosCradle $ single "B.hs" , biosTestCase "simple-bios-shell-deps" $ runTestEnv "./simple-bios-shell" $ do@@ -224,7 +224,7 @@ biosTestCaseAll "failing-cabal" $ runTestEnv "./failing-cabal" $ do attemptCabalSingleTargetLoad "MyLib.hs" assertCradleError (\CradleError {..} -> do- cradleErrorExitCode @?= ExitFailure 1+ cradleErrorExitCode @?= Right (ExitFailure 1) cradleErrorDependencies `shouldMatchList` ["failing-cabal.cabal", "cabal.project", "cabal.project.local"]) , biosTestCaseMulti "failing-cabal-multi-repl-with-shrink-error-files" $ runTestEnv "./failing-multi-repl-cabal-project" $ do attemptCabalLoad "multi-repl-cabal-fail/app/Main.hs" ["multi-repl-cabal-fail/src/Lib.hs", "multi-repl-cabal-fail/src/Fail.hs", "NotInPath.hs"]@@ -233,7 +233,7 @@ if multiSupported then assertCradleError (\CradleError {..} -> do- cradleErrorExitCode @?= ExitFailure 1+ cradleErrorExitCode @?= Right (ExitFailure 1) cradleErrorDependencies `shouldMatchList` ["cabal.project","cabal.project.local","multi-repl-cabal-fail.cabal"] -- NotInPath.hs does not match the cradle for `app/Main.hs`, so it should not be tried. (makeRelative root <$> cradleErrorLoadingFiles) `shouldMatchList` ["multi-repl-cabal-fail/app/Main.hs","multi-repl-cabal-fail/src/Fail.hs","multi-repl-cabal-fail/src/Lib.hs"])@@ -241,12 +241,17 @@ return () , biosTestCaseAll "simple-cabal" $ runTestEnv "./simple-cabal" $ do testDirectoryM isCabalCradle $ single "B.hs"+ , ignoreOnWindows $ expectBrokenBeforeCabal320 cabalDep $+ testGroup "simple-cabal with UTF-8 文档"+ $ biosTestsForAllModes [LoadUnitsInferred, LoadUnitsFromCradle] $+ runTestEnv "./cabal-with-utf-8-文档" $ do+ testDirectoryM isCabalCradle $ single "src/B.hs" , biosTestCaseMulti "build-dir" $ runTestEnv "./simple-cabal" $ do initCradle "B.hs" assertCradle isCabalCradle root <- askRoot- buildDir <- liftIO $ do- cacheDir <- resolveCacheDir "" Nothing+ cacheDir <- askCacheRootDir+ CacheDir buildDir <- liftIO $ do cabalBuildDir cacheDir root -- use --multi-repl, as that was the codepath with the bug loadFileGhc $ TargetWithContext "B.hs" []@@ -259,7 +264,7 @@ assertBool "build dir does not exist" buildDirExists , biosTestCase "custom cache dir" $ runTestEnv "./simple-cabal" $ withSystemTempDirectory "hie-bios-custom-cache-dir" $ \cacheRoot -> do- initCradleWithConfig defaultCradleRunConfig { cradleCacheDir = Just (CacheDir cacheRoot) } "B.hs"+ initCradleWithConfig defaultCradleRunConfig { cradleCacheRootDir = Just (CacheRootDir cacheRoot) } "B.hs" assertCradle isCabalCradle loadComponentOptions $ TargetWithContext "B.hs" [] _ <- assertLoadSuccess@@ -502,7 +507,7 @@ biosTestCase "failing-stack" $ runTestEnv "./failing-stack" $ do stackAttemptLoad "src/Lib.hs" assertCradleError $ \CradleError {..} -> do- cradleErrorExitCode @?= ExitFailure 1+ cradleErrorExitCode @?= Right (ExitFailure 1) cradleErrorDependencies `shouldMatchList` ["failing-stack.cabal", "stack.yaml", "package.yaml"] , biosTestCase "simple-stack" $ runTestEnv "./simple-stack" $ do testDirectoryM isStackCradle $ single "B.hs"@@ -604,13 +609,22 @@ infix 1 `shouldMatchList` biosTestCase :: TestName -> (TestConfig -> Assertion) -> TestTree-biosTestCase name assertion = askOption @VerboseLogging (\case- VerboseLogging verbose ->- testCaseSteps name (\ stepF -> testWrapper verbose stepF)- )- where- testWrapper verbose stepF =- assertion defConfig{testVerbose=verbose,testStepFunction=stepF}+biosTestCase name assertion =+ askOption @VerboseLogging+ ( \verbose ->+ askOption @KeepTempFiles+ ( \keep ->+ testCaseSteps name (\stepF -> testWrapper verbose keep stepF)+ )+ )+ where+ testWrapper verbose keep stepF =+ assertion+ defConfig+ { testVerbose = verbose+ , testStepFunction = stepF+ , testKeepTempFiles = keep+ } biosTestCaseMulti :: TestName -> (TestConfig -> Assertion) -> TestTree biosTestCaseMulti name act = testGroup name $ biosTestsForAllModes [LoadFileWithContext .. ] act@@ -713,44 +727,6 @@ tg -- --------------------------------------------------------------------- Run test-suite ignoring run-time tool dependencies.--- Can be used to force CI to run the whole test-suite.--- Makes sure that the full test-suite is being run on a properly configured--- environment.--- ---------------------------------------------------------------------- | This option, when set to 'True', specifies that we should run in the--- «list tests» mode-newtype IgnoreToolDeps = IgnoreToolDeps Bool- deriving (Eq, Ord)--instance Tasty.IsOption IgnoreToolDeps where- defaultValue = IgnoreToolDeps False- parseValue = fmap IgnoreToolDeps . Tasty.safeReadBool- optionName = pure "ignore-tool-deps"- optionHelp = pure "Run tests whether their tool dependencies exist or not"- optionCLParser = Tasty.flagCLParser Nothing (IgnoreToolDeps True)---- | The ingredient that provides the "ignore missing run-time dependencies" functionality-ignoreToolTests :: Tasty.Ingredient-ignoreToolTests = Tasty.TestManager [Tasty.Option (Proxy :: Proxy IgnoreToolDeps)] $- \_opts _tree -> Nothing--newtype VerboseLogging = VerboseLogging Bool--instance Tasty.IsOption VerboseLogging where- defaultValue = VerboseLogging False- parseValue = fmap VerboseLogging . Tasty.safeReadBool- optionName = pure "debug"- optionHelp = pure "Run the tests with verbose logging"- optionCLParser = Tasty.flagCLParser Nothing (VerboseLogging True)---- | The ingredient that provides the "ignore missing run-time dependencies" functionality-verboseLogging :: Tasty.Ingredient-verboseLogging = Tasty.TestManager [Tasty.Option (Proxy :: Proxy VerboseLogging)] $- \_opts _tree -> Nothing---- ------------------------------------------------------------------ -- Ignore test group if not supported by any stackage snapshot -- ------------------------------------------------------------------ @@ -761,14 +737,28 @@ #endif tt +ignoreOnWindows :: TestTree -> TestTree+ignoreOnWindows tt =+ if isWindows+ then ignoreTestBecause "Not supported on windows" tt+ else tt+ expectBrokenOnCabal318 :: ToolDependency -> TestTree -> TestTree expectBrokenOnCabal318 td tt =- if traceShowId (traceShowId (toolVersion td) >= Just (makeVersion [3,17,0,0]))+ if Just (makeVersion [3,17,0,0]) <= toolVersion td then expectFailBecause- ("cabal 3.18 passes all options using response files. \- If old lib:Cabal versions are used, we can't pass '--keep-temp-files' because the configure step rejects it. \- Thus, the response files are deleted before we can parse them. Falling back to the ghc shim wrapper doesn't work either \- since all arguments are passed via response files and we can't see the first argument to be '--interactive' and the wrapper fails.\+ ("cabal 3.18 passes all options using response files.\n\+ If old lib:Cabal versions are used, we can't pass '--keep-temp-files' because the configure step rejects it.\n\+ Thus, the response files are deleted before we can parse them. Falling back to the ghc shim wrapper doesn't work either\n\+ since all arguments are passed via response files and we can't see the first argument to be '--interactive' and the wrapper fails.\n\ "+ ) tt+ else tt++expectBrokenBeforeCabal320 :: ToolDependency -> TestTree -> TestTree+expectBrokenBeforeCabal320 td tt =+ if toolVersion td < Just (makeVersion [3,19,0,0])+ then expectFailBecause+ ("cabal <3.19 (before https://github.com/haskell/cabal/pull/12574) doesn't encode the arguments using UTF-8." ) tt else tt
tests/ParserTests.hs view
@@ -1,24 +1,19 @@ {-# LANGUAGE OverloadedStrings #-}-{-# LANGUAGE CPP #-} {-# LANGUAGE ScopedTypeVariables #-} module Main where -import Test.Tasty-import Test.Tasty.HUnit-import HIE.Bios.Config-#if MIN_VERSION_aeson(2,0,0)-import Data.Aeson.Key ( Key )+import Control.Applicative ((<|>))+import Control.Exception+import Data.Aeson.Key (Key) import qualified Data.Aeson.KeyMap as Map-#else-import qualified Data.HashMap.Strict as Map-import qualified Data.Text as T-#endif+import Data.Aeson.Types (JSONPathElement (..))+import Data.Typeable import Data.Void import Data.Yaml+import HIE.Bios.Config import System.FilePath-import Control.Applicative ( (<|>) )-import Control.Exception-import Data.Typeable+import Test.Tasty+import Test.Tasty.HUnit configDir :: FilePath configDir = "tests/configs"@@ -105,8 +100,31 @@ ,("./vendor", StackType (Just "parser-tests") Nothing Nothing)])) , assertParser "stack-with-load.yaml" (noDeps (Stack (StackType Nothing Nothing (Just ["lib:hie-bios","parser-tests","some-other"]))))+ -- Unknown keys are ignored, with a warning, rather than rejected (#344)+ , assertParser "cabal-unknown-key.yaml" (noDeps (Cabal $ CabalType (Just "lib:hie-bios") Nothing Nothing))+ , assertWarnings "cabal-unknown-key.yaml"+ [UnknownKeys [Key "cradle", Key "cabal"] ["futureOption"] ["cabalProject", "component", "components", "componentsToLoad"]]+ , assertParser "multi-unknown-keys.yaml"+ (noDeps (Multi [ ("./src", CradleConfig [] (CabalMulti (CabalType Nothing Nothing Nothing)+ [("./src", CabalType (Just "lib:hie-bios") Nothing Nothing)]))+ , ("./test", CradleConfig [] (Bios (Program "program") Nothing Nothing))+ ]))+ , assertWarnings "multi-unknown-keys.yaml"+ [ UnknownKeys [ Key "cradle", Key "multi", Index 0, Key "config"+ , Key "cradle", Key "cabal", Key "components", Index 0 ]+ ["extra"]+ ["path", "component", "cabalProject"]+ , UnknownKeys [Key "cradle", Key "multi", Index 1, Key "config", Key "cradle", Key "bios"] ["unknown"]+ ["program", "shell", "dependency-program", "dependency-shell", "with-ghc"]+ ]+ , assertWarnings "cabal-1.yaml" [] ] +assertWarnings :: FilePath -> [ConfigWarning] -> TestTree+assertWarnings fp expected = testCase (fp ++ " (warnings)") $ do+ (warnings, _ :: Config Void) <- readConfigWithWarnings (configDir </> fp)+ warnings @?= expected+ assertParser :: FilePath -> Config Void -> TestTree assertParser fp cc = testCase fp $ do conf <- readConfig (configDir </> fp)@@ -181,11 +199,3 @@ ] type Selector a = a -> Bool---- --------------------------------------------------------------------- Helper functions to support aeson < 2--- --------------------------------------------------------------------#if !MIN_VERSION_aeson(2,0,0)-type Key = T.Text-#endif
tests/Utils.hs view
@@ -4,6 +4,14 @@ {-# LANGUAGE ScopedTypeVariables #-} module Utils (+ -- * Tasty ingredients+ IgnoreToolDeps(..),+ VerboseLogging(..),+ KeepTempFiles(..),+ ignoreToolTests,+ verboseLogging,+ keepTempFiles,+ -- * Test Environment TestM, TestEnv,@@ -36,6 +44,7 @@ askLibDirResult, askGhcVersion, askGhcVersionResult,+ askCacheRootDir, -- * Test setup helpers step,@@ -74,11 +83,16 @@ findCradleForModuleM, ) where +import Colog.Core import qualified Colog.Core as L+import qualified Control.Exception as C import Control.Monad import Control.Monad.IO.Class import Control.Monad.Trans.State+import Data.Function ((&)) import Data.List+import Data.Proxy+import qualified Data.Text as Text import Data.Void import qualified GHC as G import HIE.Bios.Cradle@@ -92,14 +106,12 @@ import HIE.Bios.Types as HIE import Prettyprinter import System.Directory+import System.Environment (lookupEnv) import System.FilePath import System.IO.Temp import Test.Tasty.HUnit-import Colog.Core-import qualified Data.Text as Text-import Data.Function ((&))-import qualified Control.Exception as C-import System.Environment (lookupEnv)+import qualified Test.Tasty.Ingredients as Tasty+import qualified Test.Tasty.Options as Tasty -- --------------------------------------------------------------------------- -- Test configuration and information@@ -110,9 +122,10 @@ data TestConfig = TestConfig { useTemporaryDirectory :: Bool , testProjectRoots :: FilePath- , testVerbose :: Bool+ , testVerbose :: VerboseLogging , testStepFunction :: String -> IO () , testLoadModeConfig :: LoadMode+ , testKeepTempFiles :: KeepTempFiles } data TestEnv ext = TestEnv@@ -121,6 +134,7 @@ , testLibDirResult :: Maybe (CradleLoadResult FilePath) , testGhcVersionResult :: Maybe (CradleLoadResult String) , testRootDir :: FilePath+ , testCacheRootDir :: CacheRootDir , testLogger :: L.LogAction IO (L.WithSeverity HIE.Log) , testLoadMode :: LoadMode }@@ -130,9 +144,10 @@ TestConfig { useTemporaryDirectory = True , testProjectRoots = "./tests/projects"- , testVerbose = False+ , testVerbose = VerboseLogging False , testStepFunction = unLogAction logStringStderr , testLoadModeConfig = LoadFile+ , testKeepTempFiles = KeepTempFiles False } runTestEnv :: FilePath -> TestM a -> TestConfig -> IO a@@ -145,34 +160,40 @@ runTestEnvLocal fp act testConf = runTestEnv' testConf{useTemporaryDirectory = False} fp act runTestEnv' :: TestConfig -> FilePath -> TestM a -> IO a-runTestEnv' config root act = do+runTestEnv' config localDir act = do+ mkeep <- lookupEnv "KEEP_TEMP_DIRS"+ let keepTempDirs = mkeep == Just "true" || getKeepTempFiles (testKeepTempFiles config) -- We need to copy over the directory to somewhere outside the source tree -- when we test, since the cabal.project/stack.yaml/hie.yaml file in the root -- of this repository interferes with the test cradles! let wrapper r cont = if useTemporaryDirectory config- then do- mkeep <- lookupEnv "KEEP_TEMP_DIRS"- withTempCopy (mkeep == Just "true") r cont- else cont r- mkEnv root' =+ then+ withTempCopy keepTempDirs r cont+ else+ cont r++ mkEnv root' cacheDir = TestEnv { testCradleType = Nothing , testLoadResult = Nothing , testLibDirResult = Nothing , testGhcVersionResult = Nothing , testRootDir = root'+ , testCacheRootDir = cacheDir , testLogger = init_logger , testLoadMode = testLoadModeConfig config }- realRoot <- makeAbsolute $ testProjectRoots config </> root- wrapper realRoot $ \root' -> flip evalStateT (mkEnv root') $ do- step $ "Run test in: " <> root'- act+ localDirAbs <- makeAbsolute $ testProjectRoots config </> localDir+ withTempCacheRoot keepTempDirs $ \ cacheRootDir -> do+ wrapper localDirAbs $ \root -> flip evalStateT (mkEnv root cacheRootDir) $ do+ step $ "Run test in: " <> root+ step $ "Cache dir: " <> unCacheRootDir cacheRootDir+ act where init_logger = LogAction (testStepFunction config) & L.cmap printLog- & L.filterBySeverity (if testVerbose config then Debug else Error) getSeverity+ & L.filterBySeverity (if getVerboseLogging (testVerbose config) then Debug else Error) getSeverity printLog (L.WithSeverity l sev) = "[" ++ show sev ++ "] " ++ show (pretty l) -- ---------------------------------------------------------------------------@@ -269,6 +290,9 @@ askLoadMode :: TestM LoadMode askLoadMode = gets testLoadMode +askCacheRootDir :: TestM CacheRootDir+askCacheRootDir = gets testCacheRootDir+ -- --------------------------------------------------------------------------- -- Test setup helpers -- ---------------------------------------------------------------------------@@ -299,7 +323,14 @@ liftIO $ findCradle a_fp initCradle :: FilePath -> TestM ()-initCradle = initCradleWithConfig defaultCradleRunConfig+initCradle fp = do+ cacheLoc <- gets testCacheRootDir+ let+ conf =+ CradleRunConfig+ { cradleCacheRootDir = Just cacheLoc+ }+ initCradleWithConfig conf fp initCradleWithConfig :: CradleRunConfig -> FilePath -> TestM () initCradleWithConfig config fp = do@@ -317,10 +348,16 @@ initImplicitCradle :: FilePath -> TestM () initImplicitCradle fp = do+ cacheLoc <- gets testCacheRootDir+ let+ conf =+ CradleRunConfig+ { cradleCacheRootDir = Just cacheLoc+ } a_fp <- normFile fp step $ "Loading implicit Cradle for: " <> fp logger <- askLogger- crd <- liftIO $ loadImplicitCradle logger a_fp+ crd <- liftIO $ loadImplicitCradleWithConfig logger conf a_fp setCradle crd loadComponentOptions :: TargetWithContext -> TestM ()@@ -364,9 +401,8 @@ step "Cradle load" loadComponentOptions target opts <- assertLoadSuccess- root <- askRoot- -- Tests run in parallel, so isolate the interface-file cache per test root.- let ifaceCacheRoot = CacheDir (root </> "ghc-iface-cache")+ ifaceCacheRoot <- askCacheRootDir+ step $ "loadFileGhc with Cache Dir: " ++ unCacheRootDir ifaceCacheRoot liftIO $ G.runGhc (Just libdir) $ do let (ini, _) = initSessionWithMessage' (Just ifaceCacheRoot) (Just G.batchMsg) opts@@ -485,21 +521,46 @@ -- --------------------------------------------------------------------------- withTempCopy :: Bool -> FilePath -> (FilePath -> IO a) -> IO a-withTempCopy keep srcDir f = getCanonicalTemporaryDirectory >>= \targetDir -> do+withTempCopy keep srcDir f = getCanonicalTemporaryDirectory >>= \mainTmpDir -> do C.bracket- (liftIO (createTempDirectory targetDir template))- cleanup $ \newDir -> do+ (do+ let+ hieBiosMainTestDir = mainTmpDir </> hIE_BIOS_TEMP_DIR_ROOT+ createDirectoryIfMissing True hieBiosMainTestDir+ createTempDirectory hieBiosMainTestDir template+ )+ cleanup $ \ newDir -> do exists <- doesDirectoryExist srcDir when exists $ do copyDir srcDir newDir f newDir where- template = "hie-bios-test"- cleanup dir | keep = return ()- | otherwise = (liftIO . ignoringIOErrors . removeDirectoryRecursive) dir+ template = takeFileName $ dropTrailingPathSeparator srcDir+ cleanup dir+ | keep = return ()+ | otherwise = ignoringIOErrors $ removeDirectoryRecursive dir ignoringIOErrors ioe = ioe `C.catch` (\e -> const (return ()) (e :: IOError)) +withTempCacheRoot :: Bool -> (CacheRootDir -> IO a) -> IO a+withTempCacheRoot keep f = getCanonicalTemporaryDirectory >>= \mainTmpDir -> do+ C.bracket+ (do+ let+ hieBiosMainTestDir = mainTmpDir </> hIE_BIOS_TEMP_DIR_ROOT+ createDirectoryIfMissing True hieBiosMainTestDir+ CacheRootDir <$> createTempDirectory hieBiosMainTestDir "cache"+ )+ cleanup+ f+ where+ cleanup (CacheRootDir dir)+ | keep = return ()+ | otherwise = ignoringIOErrors $ removeDirectoryRecursive dir+ ignoringIOErrors ioe = ioe `C.catch` (\e -> const (return ()) (e :: IOError)) +hIE_BIOS_TEMP_DIR_ROOT :: String+hIE_BIOS_TEMP_DIR_ROOT = "hie-bios"+ copyDir :: FilePath -> FilePath -> IO () copyDir src dst = do contents <- listDirectory src@@ -513,3 +574,62 @@ else copyFile srcFp dstFp where ignored = ["dist", "dist-newstyle", ".stack-work"]++---------------------------------------------------------------------+-- Tasty runners+---------------------------------------------------------------------++-- ------------------------------------------------------------------+-- Run test-suite ignoring run-time tool dependencies.+-- Can be used to force CI to run the whole test-suite.+-- Makes sure that the full test-suite is being run on a properly configured+-- environment.+-- ------------------------------------------------------------------++-- | This option, when set to 'True', specifies that we should+-- run tests with tool dependencies regardless whether the tools are present.+--+-- While for local development, you want to ignore tests that require more setup+-- (e.g., having a GHC 9.4.8 installed), on CI we want to fail if this dependency is missing.+newtype IgnoreToolDeps = IgnoreToolDeps Bool+ deriving (Eq, Ord)++instance Tasty.IsOption IgnoreToolDeps where+ defaultValue = IgnoreToolDeps False+ parseValue = fmap IgnoreToolDeps . Tasty.safeReadBool+ optionName = pure "ignore-tool-deps"+ optionHelp = pure "Run tests whether their tool dependencies exist or not"+ optionCLParser = Tasty.flagCLParser Nothing (IgnoreToolDeps True)++-- | The ingredient that provides the "ignore missing run-time dependencies" functionality+ignoreToolTests :: Tasty.Ingredient+ignoreToolTests = Tasty.TestManager [Tasty.Option (Proxy :: Proxy IgnoreToolDeps)] $+ \_opts _tree -> Nothing++newtype VerboseLogging = VerboseLogging { getVerboseLogging :: Bool }++instance Tasty.IsOption VerboseLogging where+ defaultValue = VerboseLogging False+ parseValue = fmap VerboseLogging . Tasty.safeReadBool+ optionName = pure "debug"+ optionHelp = pure "Run the tests with verbose logging"+ optionCLParser = Tasty.flagCLParser Nothing (VerboseLogging True)++-- | The ingredient that provides the "ignore missing run-time dependencies" functionality+verboseLogging :: Tasty.Ingredient+verboseLogging = Tasty.TestManager [Tasty.Option (Proxy :: Proxy VerboseLogging)] $+ \_opts _tree -> Nothing++newtype KeepTempFiles = KeepTempFiles { getKeepTempFiles :: Bool }++instance Tasty.IsOption KeepTempFiles where+ defaultValue = KeepTempFiles False+ parseValue = fmap KeepTempFiles . Tasty.safeReadBool+ optionName = pure "keep-temp-files"+ optionHelp = pure "Keep temporary files after the run"+ optionCLParser = Tasty.flagCLParser Nothing (KeepTempFiles True)++-- | The ingredient that provides the "ignore missing run-time dependencies" functionality+keepTempFiles :: Tasty.Ingredient+keepTempFiles = Tasty.TestManager [Tasty.Option (Proxy :: Proxy KeepTempFiles)] $+ \_opts _tree -> Nothing
+ tests/configs/cabal-unknown-key.yaml view
@@ -0,0 +1,4 @@+cradle:+ cabal:+ component: "lib:hie-bios"+ futureOption: true
+ tests/configs/multi-unknown-keys.yaml view
@@ -0,0 +1,16 @@+cradle:+ multi:+ - path: "./src"+ config:+ cradle:+ cabal:+ components:+ - path: "./src"+ component: "lib:hie-bios"+ extra: 1+ - path: "./test"+ config:+ cradle:+ bios:+ program: "program"+ unknown: "x"
wrappers/cabal view
@@ -1,10 +1,10 @@-#!/usr/bin/env bash+#!/bin/sh -function out(){- echo "$1" >> "$HIE_BIOS_OUTPUT"+out(){+ printf "%s\n" "$1" >> "$HIE_BIOS_OUTPUT" } -if [ "$1" == "--interactive" ]; then+if [ "$1" = "--interactive" ]; then out "$(pwd)" for arg in "$@"; do out "$arg"
wrappers/cabal-with-repl view
@@ -1,7 +1,7 @@-#!/usr/bin/env bash+#!/bin/sh -function out(){- echo "$1" >> "$HIE_BIOS_OUTPUT"+out(){+ printf "%s\n" "$1" >> "$HIE_BIOS_OUTPUT" } out "$(pwd)"