Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion hie-bios.cabal
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ library
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,
Expand Down
19 changes: 15 additions & 4 deletions src/HIE/Bios/Config.hs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
-- | Logic and datatypes for parsing @hie.yaml@ files.
module HIE.Bios.Config(
readConfig,
readConfigWithWarnings,
ConfigWarning(..),
Config(..),
CradleConfig(..),
CabalType,
Expand All @@ -28,7 +30,7 @@ import Data.Aeson (JSONPath)
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


Expand Down Expand Up @@ -150,12 +152,21 @@ instance Show (CradleTree a) where
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
Comment thread
fendor marked this conversation as resolved.
Resolved
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
Expand Down
145 changes: 87 additions & 58 deletions src/HIE/Bios/Config/YAML.hs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE CPP #-}

-- | Datatypes for parsing @hie.yaml@ files
module HIE.Bios.Config.YAML
Expand All @@ -19,47 +18,85 @@ module HIE.Bios.Config.YAML
, 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

keys :: KeyMap v -> [Key]
keys = Map.keys
#endif

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
]
-- | 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)

-- 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"]

-- | 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
Expand Down Expand Up @@ -111,11 +148,10 @@ data CabalConfig

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

Expand All @@ -127,12 +163,10 @@ data CabalComponent

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
Expand All @@ -149,22 +183,19 @@ data StackComponent

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
Expand Down Expand Up @@ -203,8 +234,6 @@ parseBiosConfig obj =
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")
9 changes: 5 additions & 4 deletions src/HIE/Bios/Cradle.hs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ loadImplicitCradleWithConfig l config wfile = do
-- 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
getCradleWithConfig l config buildCustomCradle (cradleConfig, takeDirectory wfile)

Expand Down Expand Up @@ -276,9 +276,10 @@ yamlConfig fp = do
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
Expand Down
14 changes: 14 additions & 0 deletions src/HIE/Bios/Types.hs
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,16 @@ import Control.Monad.Trans.Class
#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.
--
Expand Down Expand Up @@ -112,6 +116,8 @@ data Log
| LogWithReplNotSupported [String]
| LogKeepTempFilesNotSupported [String]
| LogCabalPath !T.Text
| LogConfigWarning FilePath ConfigWarning
-- ^ Something in a @hie.yaml@ file was ignored.
deriving (Show)

instance Pretty LoadMode where
Expand Down Expand Up @@ -173,6 +179,14 @@ instance Pretty Log where
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

Expand Down
38 changes: 24 additions & 14 deletions tests/ParserTests.hs
Original file line number Diff line number Diff line change
@@ -1,18 +1,13 @@
{-# 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 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.Void
import Data.Yaml
import System.FilePath
Expand Down Expand Up @@ -105,8 +100,31 @@ main = defaultMain $
,("./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)
Expand Down Expand Up @@ -181,11 +199,3 @@ simpleCabalHelperYaml tool =
]

type Selector a = a -> Bool

-- ------------------------------------------------------------------
-- Helper functions to support aeson < 2
-- ------------------------------------------------------------------

#if !MIN_VERSION_aeson(2,0,0)
type Key = T.Text
#endif
4 changes: 4 additions & 0 deletions tests/configs/cabal-unknown-key.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
cradle:
cabal:
component: "lib:hie-bios"
futureOption: true
Loading
Loading