@@ -1,12 +1,14 @@
1{-# LANGUAGE CPP #-}
1{-# LANGUAGE CPP #-}
2-- | Prettier YAML encoding.
2-- | Prettier YAML encoding.
4−-- Since 0.8.13
4+-- @since 0.8.13
5module Data.Yaml.Pretty
5module Data.Yaml.Pretty
6 ( encodePretty
6 ( encodePretty
8 , getConfCompare
8 , getConfCompare
9 , setConfCompare
9 , setConfCompare
10 , defConfig
12 , defConfig
@@ -29,30 +31,47 @@ import qualified Data.Vector as V
29import Data.Yaml.Builder
31import Data.Yaml.Builder
32−-- Since 0.8.13
34+-- @since 0.8.13
33data Config = Config
35data Config = Config
34 { confCompare :: Text -> Text -> Ordering -- ^ Function used to sort keys in objects
36 { confCompare :: Text -> Text -> Ordering -- ^ Function used to sort keys in objects
37+ , confDropNull :: Bool
37−-- | The default configuration: do not sort objects.
40+-- | The default configuration: do not sort objects or drop keys
39−-- Since 0.8.13
42+-- @since 0.8.13
40defConfig :: Config
43defConfig :: Config
41−defConfig = Config mempty
44+defConfig = Config mempty False
44−-- Since 0.8.13
47+-- @since 0.8.13
45getConfCompare :: Config -> Text -> Text -> Ordering
48getConfCompare :: Config -> Text -> Text -> Ordering
46getConfCompare = confCompare
49getConfCompare = confCompare
48−-- |
51+-- | Sets ordering for object keys
49−-- Since 0.8.13
53+-- @since 0.8.13
50setConfCompare :: (Text -> Text -> Ordering) -> Config -> Config
54setConfCompare :: (Text -> Text -> Ordering) -> Config -> Config
51setConfCompare cmp c = c { confCompare = cmp }
55setConfCompare cmp c = c { confCompare = cmp }
59+getConfDropNull :: Config -> Bool
60+getConfDropNull = confDropNull
62+-- | Drop entries with `Null` value from objects, if set to `True`
65+setConfDropNull :: Bool -> Config -> Config
66+setConfDropNull m c = c { confDropNull = m }
53pretty :: Config -> Value -> YamlBuilder
68pretty :: Config -> Value -> YamlBuilder
54pretty cfg = go
69pretty 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)
72+ | confDropNull cfg = HM.filter (/= Null)
74+ in mapping (sort $ HM.toList $ HM.map go $ select o)
56 go (Array a) = array (go <$> V.toList a)
75 go (Array a) = array (go <$> V.toList a)
57 go Null = null
76 go Null = null
58 go (String s) = string s
77 go (String s) = string s
@@ -61,6 +80,6 @@ pretty cfg = go
62-- | Configurable 'encode'.
81-- | Configurable 'encode'.
64−-- Since 0.8.13
83+-- @since 0.8.13
65encodePretty :: ToJSON a => Config -> a -> ByteString
84encodePretty :: ToJSON a => Config -> a -> ByteString
66encodePretty cfg = toByteString . pretty cfg . toJSON
85encodePretty cfg = toByteString . pretty cfg . toJSON