1{-# LANGUAGE OverloadedStrings #-}23-- | Canonical formatter for scfg configurations.4module Data.Scfg.Formatter (format) where56import Data.Scfg.Types7import Data.Text (Text)8import qualified Data.Text as T910{- | Format a 'Config' as canonical scfg text. All words are11double-quoted and blocks are indented with tabs.12-}13format :: [Directive] -> Text14format = foldMap (formatDirective 0)1516formatDirective :: Int -> Directive -> Text17formatDirective depth d =18 indent19 <> quoteWord (directiveName d)20 <> params21 <> block22 <> "\n"23 where24 indent = T.replicate depth "\t"25 params = case directiveParams d of26 [] -> ""27 ps -> " " <> T.unwords (map quoteWord ps)28 block = case directiveChildren d of29 [] -> ""30 cs ->31 " {\n"32 <> foldMap (formatDirective (depth + 1)) cs33 <> indent34 <> "}"3536quoteWord :: Text -> Text37quoteWord t = "\"" <> T.concatMap escape t <> "\""38 where39 escape '"' = "\\\""40 escape '\\' = "\\\\"41 escape c = T.singleton c