on master help sign in
Adds encodePretty option to drop null values
commit6802d681c2c3b85578cda42e62809fdccd4cadab authorSophie Herold <sophie@hemio.de> dateTue 31 Oct 2017, 14:08 (9 years ago) parent15982b6
1 file changed+29−10
Data/Yaml/Pretty.hs+29−10
Data/Yaml/Pretty.hs+29−10
@@ -1,12 +1,14 @@
11{-# LANGUAGE CPP #-}
22-- | Prettier YAML encoding.
33--
4−-- Since 0.8.13
4+-- @since 0.8.13
55module Data.Yaml.Pretty
66 ( encodePretty
77 , Config
88 , getConfCompare
99 , setConfCompare
10+ , getConfDropNull
11+ , setConfDropNull
1012 , defConfig
1113 ) where
1214
@@ -29,30 +31,47 @@ import qualified Data.Vector as V
2931import Data.Yaml.Builder
3032
3133-- |
32−-- Since 0.8.13
34+-- @since 0.8.13
3335data Config = Config
3436 { confCompare :: Text -> Text -> Ordering -- ^ Function used to sort keys in objects
37+ , confDropNull :: Bool
3538 }
3639
37−-- | The default configuration: do not sort objects.
40+-- | The default configuration: do not sort objects or drop keys
3841--
39−-- Since 0.8.13
42+-- @since 0.8.13
4043defConfig :: Config
41−defConfig = Config mempty
44+defConfig = Config mempty False
4245
4346-- |
44−-- Since 0.8.13
47+-- @since 0.8.13
4548getConfCompare :: Config -> Text -> Text -> Ordering
4649getConfCompare = confCompare
4750
48−-- |
49−-- Since 0.8.13
51+-- | Sets ordering for object keys
52+--
53+-- @since 0.8.13
5054setConfCompare :: (Text -> Text -> Ordering) -> Config -> Config
5155setConfCompare cmp c = c { confCompare = cmp }
5256
57+-- |
58+-- @since 0.8.24
59+getConfDropNull :: Config -> Bool
60+getConfDropNull = confDropNull
61+
62+-- | Drop entries with `Null` value from objects, if set to `True`
63+--
64+-- @since 0.8.24
65+setConfDropNull :: Bool -> Config -> Config
66+setConfDropNull m c = c { confDropNull = m }
67+
5368pretty :: Config -> Value -> YamlBuilder
5469pretty cfg = go
55− where go (Object o) = mapping (sortBy (confCompare cfg `on` fst) $ HM.toList $ HM.map go o)
70+ where go (Object o) = let sort = sortBy (confCompare cfg `on` fst)
71+ select
72+ | confDropNull cfg = HM.filter (/= Null)
73+ | otherwise = id
74+ in mapping (sort $ HM.toList $ HM.map go $ select o)
5675 go (Array a) = array (go <$> V.toList a)
5776 go Null = null
5877 go (String s) = string s
@@ -61,6 +80,6 @@ pretty cfg = go
6180
6281-- | Configurable 'encode'.
6382--
64−-- Since 0.8.13
83+-- @since 0.8.13
6584encodePretty :: ToJSON a => Config -> a -> ByteString
6685encodePretty cfg = toByteString . pretty cfg . toJSON