{-# LANGUAGE OverloadedStrings #-}
module Text.Pandoc.Filter.Pyplot.Configuration (
configuration
, writeConfig
, inclusionKeys
, directoryKey
, captionKey
, dpiKey
, includePathKey
, saveFormatKey
, withLinksKey
, isTightBboxKey
, isTransparentKey
) where
import Data.Default.Class (def)
import Data.Maybe (fromMaybe)
import Data.String (fromString)
import qualified Data.Text.IO as TIO
import Data.Yaml
import Data.Yaml.Config (ignoreEnv, loadYamlSettings)
import System.Directory (doesFileExist)
import Text.Pandoc.Filter.Pyplot.Types
data ConfigPrecursor
= ConfigPrecursor
{ defaultDirectory_ :: FilePath
, defaultIncludePath_ :: Maybe FilePath
, defaultWithLinks_ :: Bool
, defaultSaveFormat_ :: String
, defaultDPI_ :: Int
, tightBbox_ :: Bool
, transparent_ :: Bool
, interpreter_ :: String
, flags_ :: [String]
}
instance FromJSON ConfigPrecursor where
parseJSON (Object v) =
ConfigPrecursor
<$> v .:? directoryKey .!= (defaultDirectory def)
<*> v .:? includePathKey
<*> v .:? withLinksKey .!= (defaultWithLinks def)
<*> v .:? saveFormatKey .!= (show $ defaultSaveFormat def)
<*> v .:? dpiKey .!= (defaultDPI def)
<*> v .:? isTightBboxKey .!= (isTightBbox def)
<*> v .:? isTransparentKey .!= (isTransparent def)
<*> v .:? "interpreter" .!= (interpreter def)
<*> v .:? "flags" .!= (flags def)
parseJSON _ = fail "Could not parse the configuration"
renderConfiguration :: ConfigPrecursor -> IO Configuration
renderConfiguration prec = do
includeScript <- fromMaybe mempty $ TIO.readFile <$> defaultIncludePath_ prec
let saveFormat' = fromString $ defaultSaveFormat_ prec
return $ Configuration
{ defaultDirectory = defaultDirectory_ prec
, defaultIncludeScript = includeScript
, defaultSaveFormat = saveFormat'
, defaultWithLinks = defaultWithLinks_ prec
, defaultDPI = defaultDPI_ prec
, isTightBbox = tightBbox_ prec
, isTransparent = transparent_ prec
, interpreter = interpreter_ prec
, flags = flags_ prec
}
configuration :: FilePath -> IO Configuration
configuration fp = loadYamlSettings [fp] [] ignoreEnv >>= renderConfiguration
writeConfig :: FilePath -> Configuration -> IO ()
writeConfig fp config = do
fileExists <- doesFileExist fp
if fileExists
then error $ mconcat ["File ", fp, " already exists."]
else encodeFile fp config