on de41665 help sign in
66 lines 1.6 kB history raw
1{-# LANGUAGE CPP #-}
2-- | Prettier YAML encoding.
3--
4-- Since 0.8.13
5module Data.Yaml.Pretty
6 ( encodePretty
7 , Config
8 , getConfCompare
9 , setConfCompare
10 , defConfig
11 ) where
13import Prelude hiding (null)
15#if !MIN_VERSION_base(4,8,0)
16import Control.Applicative ((<$>))
17#endif
18import Data.Aeson.Types
19import Data.ByteString (ByteString)
20import Data.Function (on)
21import qualified Data.HashMap.Strict as HM
22import Data.List (sortBy)
23#if !MIN_VERSION_base(4,8,0)
24import Data.Monoid
25#endif
26import Data.Text (Text)
27import qualified Data.Vector as V
29import Data.Yaml.Builder
31-- |
32-- Since 0.8.13
33data Config = Config
34 { confCompare :: Text -> Text -> Ordering -- ^ Function used to sort keys in objects
35 }
37-- | The default configuration: do not sort objects.
38--
39-- Since 0.8.13
40defConfig :: Config
41defConfig = Config mempty
43-- |
44-- Since 0.8.13
45getConfCompare :: Config -> Text -> Text -> Ordering
46getConfCompare = confCompare
48-- |
49-- Since 0.8.13
50setConfCompare :: (Text -> Text -> Ordering) -> Config -> Config
51setConfCompare cmp c = c { confCompare = cmp }
53pretty :: Config -> Value -> YamlBuilder
54pretty cfg = go
55 where go (Object o) = mapping (sortBy (confCompare cfg `on` fst) $ HM.toList $ HM.map go o)
56 go (Array a) = array (go <$> V.toList a)
57 go Null = null
58 go (String s) = string s
59 go (Number n) = scientific n
60 go (Bool b) = bool b
62-- | Configurable 'encode'.
63--
64-- Since 0.8.13
65encodePretty :: ToJSON a => Config -> a -> ByteString
66encodePretty cfg = toByteString . pretty cfg . toJSON